I wrote the following function to implement counting sort:
def CountSort( Arr, Max ):
counter, retVal = [0] * (Max + 1), []
for _ in Arr:
counter[_] += 1
for i in xrange( Max + 1 ):
retVal += [i] * counter[i]
return retVal
NOTE
The function takes the array of integer/list of integer as its first argument, and the maximum value it stores as the second. The only restriction is that the data in array should be distributed for \$0 \le x \le Max\$.
I'm not happy with it since I have to maintain two lists in memory now, namely Arr
and retVal
. I could, obviously, use the following:
# indentation preserved
pos = 0
for i in xrange( Max + 1 ):
while counter[i] > 0:
Arr[pos] = i
pos += 1
counter[i] -= 1
but it won't be as pythonic as the first one. An alternate approach is to delete the input Arr
, and recreate it:
# indentation preserved
del Arr
Arr = []
for i in xrange( Max + 1 ):
Arr += [i] * counter[i]
but this is not dissimilar to the second approach.
I'm open to suggestions on improvement of the first (or any of the latter).
collections.Counter
? \$\endgroup\$non-comparision
sorting algorithm forIntegers
. \$\endgroup\$