-
Notifications
You must be signed in to change notification settings - Fork 266
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #339 from MrWeast/feature/radix-sort-python
Create radix_sort.py
- Loading branch information
Showing
2 changed files
with
57 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |