Python Program to Implement Counting Sorting

01. Example:

def countingSorting(data, largest):
    
    c = [0]*(largest + 1)

    for i in range(len(data)):
        c[data[i]] = c[data[i]] + 1
 
    
    c[0] = c[0] - 1 
    for i in range(1, largest + 1):
        c[i] = c[i] + c[i - 1]
 
    result = [None]*len(data)
 
    for x in reversed(data):
        result[c[x]] = x
        c[x] = c[x] - 1
 
    return result
 
 
list01 = input('Enter the list of (Non-negative) numbers: ').split()
list01 = [int(x) for x in list01]

maximum = max(list01)

sortedList = countingSorting(list01, maximum)
print('nSorted list: ', end='')
print(sortedList)

Output:

Enter the list of (Non-negative) numbers: 320 420 140 500 185 60 200 80 10 100
Sorted list: [10, 60, 80, 100, 140, 185, 200, 320, 420, 500]

 

Leave a comment