Skip to content

Commit baca175

Browse files
Merge pull request #332 from rohansrivastava5491/patch-1
Added radix_Sort.py
2 parents 9312663 + 1935994 commit baca175

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Python/radix_sort.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
def countingSortForRadix(inputArray, placeValue):
2+
# We can assume that the number of digits used to represent
3+
# all numbers on the placeValue position is not grater than 10
4+
countArray = [0] * 10
5+
inputSize = len(inputArray)
6+
7+
# placeElement is the value of the current place value
8+
# of the current element, e.g. if the current element is
9+
# 123, and the place value is 10, the placeElement is
10+
# equal to 2
11+
for i in range(inputSize):
12+
placeElement = (inputArray[i] // placeValue) % 10
13+
countArray[placeElement] += 1
14+
15+
for i in range(1, 10):
16+
countArray[i] += countArray[i-1]
17+
18+
# Reconstructing the output array
19+
outputArray = [0] * inputSize
20+
i = inputSize - 1
21+
while i >= 0:
22+
currentEl = inputArray[i]
23+
placeElement = (inputArray[i] // placeValue) % 10
24+
countArray[placeElement] -= 1
25+
newPosition = countArray[placeElement]
26+
outputArray[newPosition] = currentEl
27+
i -= 1
28+
29+
return outputArray
30+
31+
def radixSort(inputArray):
32+
# Step 1 -> Find the maximum element in the input array
33+
maxEl = max(inputArray)
34+
35+
# Step 2 -> Find the number of digits in the `max` element
36+
D = 1
37+
while maxEl > 0:
38+
maxEl /= 10
39+
D += 1
40+
41+
# Step 3 -> Initialize the place value to the least significant place
42+
placeVal = 1
43+
44+
# Step 4
45+
outputArray = inputArray
46+
while D > 0:
47+
outputArray = countingSortForRadix(outputArray, placeVal)
48+
placeVal *= 10
49+
D -= 1
50+
51+
return outputArray
52+
53+
input = [2,20,61,997,1,619]
54+
print(input)
55+
sorted = radixSort(input)
56+
print(sorted)

0 commit comments

Comments
 (0)