chore(Python): added radix sort program (#328)

Co-authored-by: Arsenic <54987647+Arsenic-ATG@users.noreply.github.com>
pull/330/head
Prathima Kadari 2021-05-30 03:05:53 +05:30 committed by GitHub
parent d55f566a00
commit 00f74245fb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 0 deletions

View File

@ -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)

View File

@ -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).