# 桶排序

# 原理

求出无序集合的最大值与最小值(这里的最小值指存在负数的情况),创建对应的数组长度
    length=max+1
    这里要处理一下负数
    if min<0: 
        length+=abs(min)
该length就是桶数组的长度,并创建这个桶数组将所有值初始化为0
然后遍历无须数组,修改桶中元素的个数(桶数组所以对应的值就是无需数组中相同值的个数)
最后只需要将桶数组中值大于0的取出来放在一个新数组中即得有序数组。

# 实现

inputArr = [ 11,10,199383, 34, -1,-32,-29, 4, 0, 34, 5, 4, 36, 1, 8, 123, 453, 1008]
print("未排序集合:{0}".format(inputArr))
maxItem=inputArr[0]
minItem=inputArr[0]
for item in inputArr[1:]:
    if maxItem<item:
        maxItem=item
    if(minItem>item):
        minItem=item
# 最小值,最大值
print("min:{0}\tmax:{1}".format(minItem,maxItem))
# 创建桶数组,索引值为元素值,索引对应的值为元素个数
length=maxItem+1
if(minItem<0):
    length+=abs(minItem)
bigArr=[0]*length
for item in inputArr:
    bigArr[item]+=1
# 将桶中的数据放到对应的有序数组上
sortArr=[None]*len(inputArr)
sortIndex=0
for index in range(minItem,maxItem+1):
    if(bigArr[index]==0):
        continue
    while(bigArr[index]>0):
        sortArr[sortIndex]=index
        bigArr[index]-=1
        sortIndex+=1
print("已排序集合:{0}".format(sortArr))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32