8000 Merge pull request #26 from beingadityak/radix_sort · jeffmikels/python@68b8f89 · GitHub
[go: up one dir, main page]

Skip to content

Commit 68b8f89

Browse files
authored
Merge pull request AllAlgorithms#26 from beingadityak/radix_sort
Radix sort
2 parents 5fa8b96 + a00c1f3 commit 68b8f89

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

sorting/radix_sort.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Following is the implementation of Radix Sort.
2+
3+
4+
def radix_sort(arr, radix=10):
5+
"""
6+
:param arr: Iterable of elements to sort.
7+
:param radix: Base of input numbers
8+
:return: Sorted list of input.
9+
Time complexity: O(d * (n + b))
10+
where, n is the size of input list.
11+
b is base of representation.
12+
d is number of digits in largest number in that base.
13+
Space complexity: O(n + k)
14+
where, k is the range of input.
15+
"""
16+
max_length = False
17+
tmp, digit = -1, 1
18+
19+
while not max_length:
20+
max_length = True
21+
# declare and initialize buckets
22+
buckets = [[] for _ in range(radix)]
23+
24+
# split arr between lists
25+
for i in arr:
26+
tmp = i // digit
27+
buckets[tmp % radix].append(i)
28+
if max_length and tmp > 0:
29+
max_length = False
30+
31+
# empty lists into arr array
32+
a = 0
33+
for b in range(radix):
34+
buck = buckets[b]
35+
for i in buck:
36+
arr[a] = i
37+
a += 1
38+
39+
# move to next digit
40+
digit *= radix
41+
return arr
42+
43+
44+
def main():
45+ """
46+
Driver function to test radix sort.
47+
"""
48+
test = [170, 45, 75, 90, 802, 24, 2, 66]
49+
print('Sorted array:', radix_sort(test))
50+
51+
52+
if __name__ == '__main__':
53+
main()

0 commit comments

Comments
 (0)
0