Skip to content

Commit b6e306e

Browse files
committed
radix sort in python
1 parent 43a4f45 commit b6e306e

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

classical_algorithms/radix.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Radix:
2+
def sort(self, data):
3+
if data is None:
4+
raise TypeError('Data cannot be None')
5+
if not data:
6+
return data
7+
return self._sort(data)
8+
9+
def _sort(self, data):
10+
max_number = max(data)
11+
digits = len(str(abs(max_number)))
12+
13+
for d in range(digits):
14+
buckets = [[] for _ in range(10)]
15+
for num in data:
16+
q = num//10**d
17+
r = q % 10
18+
buckets[r].append(num)
19+
data = []
20+
for bucket in buckets:
21+
data.extend(bucket)
22+
return data
23+
24+
25+
# Ex:
26+
array = [50, 2, 13, 23, 11, 100]
27+
print(Radix().sort(array))
28+

0 commit comments

Comments
 (0)