排序---基数排序

基数排序

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
def radix_sort(a, r, bits):  
if bits == 0 or len(a) == 0:
return a

n = 1
k = bits-1
while k:
n*=10
k-=1

radixes = [[] for _ in range(r)]
for e in a:
radixes[(e//n)%10].append(e)

new_a = []
for i, radix in enumerate(radixes):
new_a.extend(radix_sort(radix, r, bits-1))

return new_a


if __name__ == "__main__":
import random
a = [random.randrange(1000) for _ in range(100)]
print(a)
new_a = radix_sort(a, 10, 3)
print(new_a)