Skip to content

Create radix_sort.py #339

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Dec 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()