如何实现适用于负数的 CountingSort?

How can I implement a CountingSort that works with negative numbers?

我在 Python 中实现了以下计数排序算法,但它不适用于包含负数的数组。有人可以帮助我吗?

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

一个简单的方法就是找到最小值并将您的索引偏移该量,以便将最小值存储在 counter 的数组索引 0 中。然后在你的 while 循环中,重新添加最小值以获得原始值:

m = min(nlist)
k = max(nlist) - m

counter = [0] * ( k + 1 )

for i in nlist:
    counter[i-m] += 1

ndx = 0;
for i in range( len( counter ) ):
    while 0 < counter[i]:
       nlist[ndx] = i+m
       ndx += 1
       counter[i] -= 1

您可以查找输入中的最低值,并将其一直添加到索引中,在构建输出时将其转换回来:

def counting(nlist):
    nlist = list(nlist)
    size = len(nlist)

    if size < 2:
        return nlist

    low = min(nlist)
    k = max(nlist) - low

    counter = [0] * ( k + 1 )

    for i in nlist:
        counter[i - low] += 1

    print(counter) # see what the counter list looks like. Remove in final version 
    ndx = 0;
    for i in range( len( counter ) ):
        while 0 < counter[i]:
            nlist[ndx] = i + low
            ndx += 1
            counter[i] -= 1

    return nlist