- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathradix_sort.py
48 lines (39 loc) · 1.18 KB
/
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
This is a pure Python implementation of the radix sort algorithm
Source: https://en.wikipedia.org/wiki/Radix_sort
"""
from __future__ importannotations
RADIX=10
defradix_sort(list_of_ints: list[int]) ->list[int]:
"""
Examples:
>>> radix_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> radix_sort(list(range(15))) == sorted(range(15))
True
>>> radix_sort(list(range(14,-1,-1))) == sorted(range(15))
True
>>> radix_sort([1,100,10,1000]) == sorted([1,100,10,1000])
True
"""
placement=1
max_digit=max(list_of_ints)
whileplacement<=max_digit:
# declare and initialize empty buckets
buckets: list[list] = [[] for_inrange(RADIX)]
# split list_of_ints between the buckets
foriinlist_of_ints:
tmp=int((i/placement) %RADIX)
buckets[tmp].append(i)
# put each buckets' contents into list_of_ints
a=0
forbinrange(RADIX):
foriinbuckets[b]:
list_of_ints[a] =i
a+=1
# move to next
placement*=RADIX
returnlist_of_ints
if__name__=="__main__":
importdoctest
doctest.testmod()