Skip to content

Commit

Permalink
Merge pull request #339 from MrWeast/feature/radix-sort-python
Browse files Browse the repository at this point in the history
Create radix_sort.py
  • Loading branch information
kelvins authored Dec 3, 2023
2 parents 5438853 + 506ae67 commit a28674a
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 2 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3276,8 +3276,8 @@ In order to achieve greater coverage and encourage more people to contribute to
</a>
</td>
<td> <!-- Python -->
<a href="./CONTRIBUTING.md">
<img align="center" height="25" src="./logos/github.svg" />
<a href="./src/python/radix_sort.py">
<img align="center" height="25" src="./logos/python.svg" />
</a>
</td>
<td> <!-- Go -->
Expand Down
55 changes: 55 additions & 0 deletions src/python/radix_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import random


def radix_sort(arr):
# Find the maximum number to know the number of digits
max_num = max(arr)

# Do counting sort for every digit, starting from the least significant digit
exp = 1
while max_num // exp > 0:
counting_sort(arr, exp)
exp *= 10


def counting_sort(arr, exp):
n = len(arr)
output = [0] * n
count = [0] * 10

for i in range(n):
index = arr[i] // exp
count[index % 10] += 1

for i in range(1, 10):
count[i] += count[i - 1]

i = n - 1
while i >= 0:
index = arr[i] // exp
output[count[index % 10] - 1] = arr[i]
count[index % 10] -= 1
i -= 1

for i in range(n):
arr[i] = output[i]


def main():
print("Fixed Testing Array")
arr = [170, 2, 45, 75, 75, 90, 802, 24, 2, 66]
print("Unsorted array:", arr)
radix_sort(arr)
print("Sorted array:", arr)

print("Random Testing Array")
arr = []
for i in range(0, 10):
arr.append(random.randint(0, 20))
print("Unsorted array:", arr)
radix_sort(arr)
print("Sorted array:", arr)


if __name__ == "__main__":
main()

0 comments on commit a28674a

Please sign in to comment.