Python Program for Counting Sort (original) (raw)

Last Updated : 28 Jul, 2022

Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence.

Python3

def countSort(arr):

`` output = [ 0 for i in range ( 256 )]

`` count = [ 0 for i in range ( 256 )]

`` ans = ["" for _ in arr]

`` for i in arr:

`` count[ ord (i)] + = 1

`` for i in range ( 256 ):

`` count[i] + = count[i - 1 ]

`` for i in range ( len (arr)):

`` output[count[ ord (arr[i])] - 1 ] = arr[i]

`` count[ ord (arr[i])] - = 1

`` for i in range ( len (arr)):

`` ans[i] = output[i]

`` return ans

arr = "geeksforgeeks"

ans = countSort(arr)

print ( "Sorted character array is %s" % ("".join(ans)))

Output:

Sorted character array is eeeefggkkorss

Time Complexity: O(n+k) where n is the number of elements in the input array and k is the range of input.
Auxiliary Space: O(n+k)

Please refer complete article on Counting Sort for more details!

Similar Reads