Skip to content

Commit 86b6c8b

Browse files
author
Ian Doarn
authored
Merge pull request OmkarPathak#78 from IanDoarn/master
Implemented Radix Sorting, thanks @ashaywalke
2 parents 6ea8635 + cbf4405 commit 86b6c8b

File tree

3 files changed

+53
-1
lines changed

3 files changed

+53
-1
lines changed

pygorithm/sorting/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from . import counting_sort
99
from . import insertion_sort
1010
from . import merge_sort
11+
from . import radix_sort
1112
from . import selection_sort
1213
from . import shell_sort
1314

@@ -19,6 +20,7 @@
1920
'insertion_sort',
2021
'merge_sort',
2122
'quick_sort',
23+
'radix_sort',
2224
'selection_sort',
2325
'shell_sort'
2426
]

pygorithm/sorting/radix_sort.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""
2+
Author: Ian Doarn
3+
Date: 31st Oct 2017
4+
5+
Reference:
6+
https://stackoverflow.com/questions/35419229/python-radix-sort
7+
"""
8+
9+
10+
def sort(_list, base=10):
11+
"""
12+
Radix Sort
13+
14+
:param _list: array to sort
15+
:param base: base radix number
16+
:return: sorted list
17+
"""
18+
# TODO: comment this
19+
20+
result_list = []
21+
power = 0
22+
while _list:
23+
bs = [[] for _ in range(base)]
24+
for x in _list:
25+
bs[x // base ** power % base].append(x)
26+
_list = []
27+
for b in bs:
28+
for x in b:
29+
if x < base ** (power + 1):
30+
result_list.append(x)
31+
else:
32+
_list.append(x)
33+
power += 1
34+
return result_list
35+
36+
37+
if __name__ == '__main__':
38+
print(sort([170, 45, 75, 90, 802, 24, 2, 66]))

tests/test_sorting.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
counting_sort,
1111
bucket_sort,
1212
shell_sort,
13-
heap_sort)
13+
heap_sort,
14+
radix_sort)
1415

1516

1617
class TestSortingAlgorithm(unittest.TestCase):
@@ -105,5 +106,16 @@ def test_heap_sort(self):
105106
self.alphaResult = heap_sort.sort(self.alphaArray)
106107
self.assertEqual(self.alphaResult, self.sorted_alpha_array)
107108

109+
110+
class TestRadixSort(TestSortingAlgorithm):
111+
def test_radix_sort(self):
112+
self.result = radix_sort.sort(self.array)
113+
self.assertEqual(self.result, self.sorted_array)
114+
115+
# TODO: Fix radix sort to sort alphabetically
116+
# self.alphaResult = radix_sort.sort(self.alphaArray)
117+
# self.assertEqual(self.alphaResult, self.sorted_alpha_array)
118+
119+
108120
if __name__ == '__main__':
109121
unittest.main()

0 commit comments

Comments
 (0)