Python 数据结构与算法——桶排序
#简单的桶排序 def bucksort(A): bucks = dict() # 定义一个桶变量,类型为字典 for i in A: bucks.setdefault(i,[]) # 每个桶默认为空列表 bucks[i].append(i) # 往对应的桶中添加对应相同元素 print(bucks) A_sort = [] for i in range(min(A), max(A)+1): if i in bucks: # 检查是否存在对应数字的桶 A_sort.extend(bucks[i]) # 合并桶中数据 return A_sort A = [2,3,5,4,6,7,3,3,0,8,5] a = bucksort(A) print(a)
#打印结果:
{2: [2], 3: [3, 3, 3], 5: [5, 5], 4: [4], 6: [6], 7: [7], 0: [0], 8: [8]}
[0, 2, 3, 3, 3, 4, 5, 5, 6, 7, 8]