计数排序算法:
计数排序是一个非基于比较的排序算法,该算法于1954年由 Harold H. Seward 提出。它的优势在于在对一定范围内的整数排序时,它的复杂度为Ο(n+k)(其中k是整数的范围),快于任何比较排序算法。 [1] 当然这是一种牺牲空间换取时间的做法,而且当O(k)>O(nlog(n))的时候其效率反而不如基于比较的排序(基于比较的排序的时间复杂度在理论上的下限是O(nlog(n)), 如归并排序,堆排序。
基本函数01定义如下:
def count_sort(input_list):
length = len(input_list)
if length < 2:
return input_list
max_num = max(input_list)
count = [0] * (max_num + 1)
for element in input_list:
count[element] += 1
output_list = []
for i in range(max_num + 1):
for j in range(count[i]):
# count[i]表示元素i出现的次数,如果有多次,通过循环重复追加
output_list.append(i)
return output_list
算法核心思想:
计数排序对输入的数据有附加的限制条件:
1、输入的线性表的元素属于有限偏序集S;
2、设输入的线性表的长度为n,|S|=k(表示集合S中元素的总数目为k),则k=O(n)。
在这两个条件下,计数排序的复杂性为O(n)。
# 计数排序算法
def CountingSort(arr, maxValue):
bucketLen = maxValue+1
bucket = [0]*bucketLen
sortedIndex =0
arrLen = len(arr)
for i in range(arrLen):
if not bucket[arr[i]]:
bucket[arr[i]]=0
bucket[arr[i]]+=1
for j in range(bucketLen):
while bucket[j]>0:
arr[sortedIndex] = j
sortedIndex+=1
bucket[j]-=1
return arr
if __name__ == '__main__':
Li = [9, 82, 17, 6, 5, 4, 3, 2, 11, 85, 6, 36, -2, -34, 29]
print("source is:", Li)
res = CountingSort(Li,max(Li))
print("sort01 is:", res)
print("sort02 is:", res[::-1])
运行结果如下:
source is: [9, 82, 17, 6, 5, 4, 3, 2, 11, 85, 6, 36, -2, -34, 29]
sort01 is: [2, 3, 4, 5, 6, 6, 9, 11, 17, 29, 36, 52, 82, 84, 85]
sort02 is: [85, 84, 82, 52, 36, 29, 17, 11, 9, 6, 6, 5, 4, 3, 2]
Process finished with exit code 0
参考资源:https://blog.csdn.net/u014597198/article/details/91395700