Python program for Radix sort

Python program for Radix sort

Following program will help university students and beginners to understand the concepts and working of Radix sort.

def countSort(array, exp): 
    n = len(array) 
    count =[]
    # The output array elements that will have sorted arr 
        index = int(array[i]//exp) 
        output[ count[ (index)%10 ] - 1] = array[i] 
        count[ int((index))%10 ] -= 1
        i -= 1
    # Copying the output array to arr[], 
    # so that arr now contains sorted numbers 
    i = 0
    for i in range(0,len(array)): 
        array[i] = output[i] 
# Method to do Radix Sort 
def Radixsort(array): 
    # Find the maximum number to know number of digits 
    maximum = max(array) 
    # Do counting sort for every digit. Note that instead 
    # of passing digit number, exp is passed. exp is 10^i 
    # where i is current digit number 
    exp = 1
    while maximum/exp > 0: 
        exp *= 10
n= int(input("enter the number of elements : "))

Output :

enter the number of elements5
enter the elements1
enter the elements2
enter the elements4
enter the elements8
enter the elements3
array before sorting [1, 2, 4, 8, 3]
array after sorting [1, 2, 3, 4, 8]

Note : Please note that above program is compatible with Python 3 or higher version.

Please check out other practical related to Data structures

1 thought on “Python program for Radix sort”

Leave a Comment