I've made the following implementation of counting sort. I don't think that I understand the algorithm fully but this implementation seems to be working correctly.
I've used the Counter
dictionary from the collections module. It seems to be the best way to handle the counting part. But I haven't seen anyone using it to implement counting sort.
Is there any way to improve the code?
from random import randrange
from collections import Counter
from copy import deepcopy
def counting_sort(aList, length):
"""
counting sort does not work for negative numbers
counting sort assumes that each element is SMALL INTEGER
running time is O(maxVal - minVal) ---> Linear
(Useful only when the difference between maxVal and minVal is not large)
"""
list_copy = deepcopy(aList) # a copy so that I can return it and check it against the original list applied to sorted function
c = Counter()
for num in list_copy:
c[num] += 1
index = 0
# for i in range(len(c)):
# while 0 < c[i]:
# list_copy[index] = i
# c[i] -= 1
# index += 1
for key in c:
while c[key] > 0:
list_copy[index] = key
c[key] -= 1
index += 1
return list_copy
aList = [randrange(100) for _ in range(1000)]
after = counting_sort(aList, len(aList))
print(after == sorted(aList))