【Python】排序算法(非比较类排序)

一、计数排序

 

"""
计数排序:
建立一个新列表temp,大小为最小值到最大值,存放数据为lst中数字number的次数
将新列表temp与lst建立关系,设置一个偏移量offect
number = index + offect
offect = min(lst)
"""
def countingSort(lst):
    minVal = min(lst)
    maxVal = max(lst)
    offect = minVal
    temp = [0] * (maxVal - minVal + 1)
    for number in lst:
        temp[number - offect] += 1
    i = 0
    for index in range(len(temp)):
        for k in range(temp[index]):
            lst[i] = index + offect
            i += 1

lst = [1,-1,2,2,3,1,1,9,7,5,6,4,3,1,5]
countingSort(lst)
print(lst)

测试结果:

猜你喜欢

转载自blog.csdn.net/trichloromethane/article/details/108837485