-
Notifications
You must be signed in to change notification settings - Fork 0
/
radix_sort.py
32 lines (28 loc) · 1010 Bytes
/
radix_sort.py
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
#—*— coding: utf-8 _*_
def radix_sort(array, base=10):
def list_to_buckets(array, base, iteration):
buckets = [[] for x in range(base)]
for number in array:
# Isolate the base-digit from the number
digit = (number // (base ** iteration)) % base
# Drop the number into the correct bucket
buckets[digit].append(number)
return buckets
def buckets_to_list(buckets):
numbers = []
for bucket in buckets:
# append the numbers in a bucket
# sequentially to the returned array
for number in bucket:
numbers.append(number)
return numbers
maxval = max(array)
it = 0
# Iterate, sorting the array by each base-digit
while base ** it <= maxval:
array = buckets_to_list(list_to_buckets(array, base, it))
it += 1
return array
#test below
A = [2, 10000, 100, 0, 2, 3, 0, 3]
print(radix_sort(A))