桶排序:按照位数放入桶中, 可以局部有序,然后分成整体有序。
def bucket_sort(li, n=100, max_num = 10000):
bucket = [[] for _ in range(n)]
for var in li:
i = min(var //(max_num // n), n-1) # i表示var放那个桶里面
buckets[i].append(var)
for j in range(len(buckets[i])-1,0,-1):
if bukcets[i][j] < buckets[i][j-1]:
buckets[i][j],buckets[i][j-1] = buckets[i][j-1],buckets[i][j]
else:
break
sorted_li = []
for buc in buckets:
sorted_li.extend(buc)
return sorted_li
根据基数排序的方法,进行计算。类似于桶排序。
def radix_sort(li):
max_num = max(li) # 最小值 9> 1,99>2,888>3
it = 0
while 10 ** it <=max_num:
buckets = [[] for _ in range(10)]
for var in li:
digit = (var // 10 ** it) % 10
buckets[digit].append(var)
# 分桶完成
li.clear()
for buc in buckets:
li.extend(buc)
# 重新写回li
it += 1