Python Counting Sort
The core of counting sort is to convert the input data values into keys and store them in an extra array space. As a sort with linear time complexity, counting sort requires that the input data must be integers with a definite range.
Example
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 = "wwwexamplecom"
ans = countSort(arr)
print ( "Character array sorted: %s" %("".join(ans)) )
The output after executing the above code is:
符数组排序 bcmnoooruwwwOther extensions
Python3 Examples