From 00f74245fb5bc3bd835aaa777de48b9dacc5dc33 Mon Sep 17 00:00:00 2001 From: Prathima Kadari Date: Sun, 30 May 2021 03:05:53 +0530 Subject: [PATCH] chore(Python): added radix sort program (#328) Co-authored-by: Arsenic <54987647+Arsenic-ATG@users.noreply.github.com> --- algorithms/Python/README.md | 1 + algorithms/Python/sorting/radix_sort.py | 47 +++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 algorithms/Python/sorting/radix_sort.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index a2d4dd27..d1caa623 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -29,6 +29,7 @@ 4. [Quicksort](sorting/quicksort.py) 5. [Selection Sort](sorting/selection_sort.py) 6. [Heap Sort](sorting/heap-sort.py) +7. [Radix Sort](sorting/radix-sort.py) ## Strings 1. [Is Good Str](strings/is_good_str.py) diff --git a/algorithms/Python/sorting/radix_sort.py b/algorithms/Python/sorting/radix_sort.py new file mode 100644 index 00000000..4bfc66cf --- /dev/null +++ b/algorithms/Python/sorting/radix_sort.py @@ -0,0 +1,47 @@ +""" +Radix Sort +Time Complexity: O(nk + n). +n is the size of input list and k is the digit length of the number. +""" + +def radix_sort(arr, simulation=False): + position = 1 + max_number = max(arr) + + iteration = 0 + if simulation: + print("iteration", iteration, ":", *arr) + + while position <= max_number: + queue_list = [list() for _ in range(10)] + + for num in arr: + digit_number = num // position % 10 + queue_list[digit_number].append(num) + + index = 0 + for numbers in queue_list: + for num in numbers: + arr[index] = num + index += 1 + + if simulation: + iteration = iteration + 1 + print("iteration", iteration, ":", *arr) + + position *= 10 + return arr + +arr = [142, 34, 6, 17, 113, 2, 261, 72] + +if __name__ == "__main__": + print("Sorted Array:", radix_sort(arr)) + +# Runtime Test Cases:- +# Test case 1. +# Enter the list of numbers: 12 7 56 42 +# Sorted list: [7 12 42 56] +# Test case 2. +# Enter the list of numbers: 142 34 6 17 113 2 261 72 +# Sorted list: [2 6 17 34 72 113 142 261] +# For radix sort, Best = Worst = Average Time Complexity is O(nk+n).