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

标签 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

最佳答案

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

关于python - 如何实现适用于负数的 CountingSort?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41324974/

相关文章:

python - 如何在 ipython 控制台中定义类输出

Java回溯问题

data-structures - 将中缀转换为前缀转换

python - 为什么到双向链表前面的递归函数不起作用?

python - PsychoPy 在 64 位操作系统上发送触发器

javascript - 使用BeautifulSoup获取 "View Element"代码而不是 "View Source"代码

algorithm - 这个算法的时间复杂度是Θ(n)吗?

c++ - 对数字列表及其索引进行排序的最快方法

c++ - 实现字符串映射

javascript - 谷歌浏览器扩展 :Call Python function from javascript