Python Program for Radix Sort
In this article we are going to see Radix Sort with Python
Radix Sort Algorithm Python
The provided Python code implements Radix Sort, a non-comparative sorting algorithm that works by distributing elements into buckets based on their individual digits. The code defines a countingSort function, which performs counting sort based on the digit represented by exp1. It maintains auxiliary arrays count and output to store intermediate results. The radixSort function orchestrates the sorting process by repeatedly applying counting sort for each digit position, from the least significant digit to the most significant digit. The driver code initializes an array, applies the radixSort function, and prints the sorted array. This algorithm’s time complexity is linear, making it suitable for large datasets with a limited range of digits.
Python3
def countingSort(arr, exp1):
n = len (arr)
output = [ 0 ] * (n)
count = [ 0 ] * ( 10 )
for i in range ( 0 , n):
index = (arr[i] / exp1)
count[ int ((index) % 10 )] + = 1
for i in range ( 1 , 10 ):
count[i] + = count[i - 1 ]
i = n - 1
while i> = 0 :
index = (arr[i] / exp1)
output[ count[ int ((index) % 10 ) ] - 1 ] = arr[i]
count[ int ((index) % 10 )] - = 1
i - = 1
i = 0
for i in range ( 0 , len (arr)):
arr[i] = output[i]
def radixSort(arr):
max1 = max (arr)
exp = 1
while max1 / / exp > 0 :
countingSort(arr,exp)
exp * = 10
arr = [ 170 , 45 , 75 , 90 , 802 , 24 , 2 , 66 ]
radixSort(arr)
for i in range ( len (arr)):
print (arr[i],end = " " )
|
Output
2 24 45 66 75 90 170 802
Time Complexity: O(n*d). Here d=10
Auxiliary Space: O(n)
Please refer complete article on Radix Sort for more details!
Last Updated :
28 Aug, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...