diff --git a/README.md b/README.md index 9def01ab..d2859132 100644 --- a/README.md +++ b/README.md @@ -3276,8 +3276,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + diff --git a/src/python/radix_sort.py b/src/python/radix_sort.py new file mode 100644 index 00000000..fc91c414 --- /dev/null +++ b/src/python/radix_sort.py @@ -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()