def counting_sort(a, k):
""" k为a数组中的最大值 """
# 构造临时缓存数组c
c = [0 for _ in range(k + 1)]
# 初始化结果数组b
b = [0 for _ in range(len(a))]
# c[a[j]] 表示的是,a[j]元素的数值在c中有对应的下标数值,则加1
# c数组中的元素代表对应下标数字在a数组中存在的个数
# c = [0, 0, 0] a = [2, 1, 1]
# >>> c = [0, 2, 1]
for n in range(0, len(a)):
c[a[n]] = c[a[n]] + 1
# 计算有多少个元素小于等于c的下标元素数值
for _ in range(1, k + 1):
c[_] = c[_] + c[_ - 1]
# a = [2, 5, 3, 0, 2, 3, 0, 3]
# c = [2, 2, 4, 7, 7, 8]
# b[c[a[8]] - 1] = b[c[3] - 1] = b[7 - 1] = a[8] = 3
# b = [0, 0, 0, 0, 0, 0, 3, 0]
# b[c[a[7]] - 1] = b[c[0] - 1] = b[2 - 1] = a[7] = 0
# b = [0, 0, 0, 0, 0, 0, 3, 0]
# b[c[a[6]] - 1] = b[c[3] - 1] = b[6 - 1] = a[6] = 3
# b = [0, 0, 0, 0, 0, 3, 3, 0]
# ...
for m in range(len(a) - 1, -1, -1):
b[c[a[m]] - 1] = a[m]
c[a[m]] = c[a[m]] - 1
return b
if __name__ == '__main__':
a = [2, 5, 3, 0, 2, 3, 0, 3]
print(counting_sort(a, 5))
# [0, 0, 2, 2, 3, 3, 3, 5]
网友评论