如何实现与负数一起使用的CountingSort?

时间:2016-12-25 22:30:23

标签: python algorithm data-structures counting-sort

我在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

2 个答案:

答案 0 :(得分:2)

一种简单的方法就是找到最小值并将索引偏移该量,以便最小值存储在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

答案 1 :(得分: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