def bucket_sort(li,n=100,max_num=10000):
"""
桶排序
:param li:
:param n: 桶的个数
:param max_num: 数字最大值
:return:
"""
buckets=[[] for _ in range(n)] #创建桶 二维列表 列表生成式生成二维列表,[[], [],...,[]]
for var in li:# # 遍历列表所有数放在合适的桶里
# i = var // (max_num // n) # i表示var放到几号桶里 86//(10000//100)=0,所以放在0号桶,99号无法处理,但是处理不了10000
i = min(var//(max_num//n),n-1)#i表示var放到几号桶里,# 为了解决10000这个数,将原i值和n-1=99作比较取小
buckets[i].append(var)#把var加到桶里边
# # 保持桶内的顺序(插入排序)
for j in range(len(buckets[i])-1,0,-1): # 在列表[4,7,2,5]从后往前倒着取值
if buckets[i][j]<buckets[i][j-1]: # 如果后面的元素小于前一个元素就交换它
buckets[i][j] , buckets[i][j - 1]=buckets[i][j-1],buckets[i][j]
else:
break
# 将桶里的数输出出来
sorted_li=[]
# buc是每一个桶
for buc in buckets:
sorted_li.extend(buc)
return sorted_li
import random
li=[random.randint(0,10000000) for i in range(100)]
print(li)
li=bucket_sort(li)
print(li)
运行结果:
[9881188, 607586, 5251727, 276608, 3917043, 7582172, 4402645, 7848910, 7256305, 533093, 50947, 3658243, 3248171, 7172962, 6474852, 472381, 8112084, 5909959, 5094276, 9448859, 977637, 5640556, 1606936, 6292502, 4953863, 9581057, 8158084, 1734567, 3912330, 9627655, 9997825, 8789174, 6303877, 3608406, 9060422, 7685655, 4981481, 5701090, 3572621, 1057251, 1726368, 4112166, 935878, 9438375, 6439280, 7084315, 3312415, 7894289, 645419, 3243931, 8495166, 5641259, 2304151, 7867234, 6593533, 7265262, 5080384, 920185, 8841155, 6596089, 3854758, 6507808, 2039231, 7210728, 7663794, 5371921, 4249748, 5515449, 3713929, 1959282, 4118036, 7421970, 1046985, 7596236, 7035902, 516403, 3154851, 1286581, 5232493, 7154591, 253623, 1679772, 1295186, 1482579, 1071470, 1137704, 1959022, 4478736, 7603872, 9221382, 3256507, 579033, 8367566, 7841685, 3445539, 185910, 5936127, 8502364, 3777253, 4387559]
[50947, 185910, 253623, 276608, 472381, 516403, 533093, 579033, 607586, 645419, 920185, 935878, 977637, 1046985, 1057251, 1071470, 1137704, 1286581, 1295186, 1482579, 1606936, 1679772, 1726368, 1734567, 1959022, 1959282, 2039231, 2304151, 3154851, 3243931, 3248171, 3256507, 3312415, 3445539, 3572621, 3608406, 3658243, 3713929, 3777253, 3854758, 3912330, 3917043, 4112166, 4118036, 4249748, 4387559, 4402645, 4478736, 4953863, 4981481, 5080384, 5094276, 5232493, 5251727, 5371921, 5515449, 5640556, 5641259, 5701090, 5909959, 5936127, 6292502, 6303877, 6439280, 6474852, 6507808, 6593533, 6596089, 7035902, 7084315, 7154591, 7172962, 7210728, 7256305, 7265262, 7421970, 7582172, 7596236, 7603872, 7663794, 7685655, 7841685, 7848910, 7867234, 7894289, 8112084, 8158084, 8367566, 8495166, 8502364, 8789174, 8841155, 9060422, 9221382, 9438375, 9448859, 9581057, 9627655, 9881188, 9997825]
Process finished with exit code 0
性能:
'''
桶排序的表现取决于数据的分布,也就是需要对不同的数据排序时采取不同的分桶策略;
n是列表的长度,k是桶的个数。
平均情况时间复杂度:O(n+k)
最坏情况时间复杂度:O(n平方k)
空间复杂度:O(nk)
'''
桶排序简单过程图: