I have the following implementation of a Counting Sort algorithm in Python, but it doesn't work with arrays that contains negative numbers. Could someone help me?
def counting(nlist):
nlist = list(nlist)
size = len(nlist)
if size < 2:
return nlist
k = max(nlist)
counter = [0] * ( k + 1 )
for i in nlist:
counter[i] += 1
ndx = 0;
for i in range( len( counter ) ):
while 0 < counter[i]:
nlist[ndx] = i
ndx += 1
counter[i] -= 1
return nlist
A simple approach would be just to find the minimum value and offset your indices by that amount, so that the minimum value is stored in array index 0 of
counter
. Then in your while loop, add the minimum value back on to get the original values: