计数排序 - 负整数

时间:2018-03-08 23:52:14

标签: python

我试图对负数进行count_sort,以下代码似乎只适用于正整数。有关如何修复它以处理负数的任何指示?

def count_sort(l):
   output = [0] * len(l)
   low = min(l)
   if low >= 0:
      low = 0
   high = max(l)
   working = [0 for i in range(low, high+1)]
   for i in l:
      workng[i] += 1
   for j in range(1, len(working)):
      working[j] += working[j-1]
   for k in reversed(ul):
      output[working[k] - 1] = k
      working[k] -= 1
   return output 

2 个答案:

答案 0 :(得分:2)

计数排序可以适用于任何有界的整数范围,它们都不需要是积极的。为了让您的代码适用于负值(并且不会浪费大量内存以获得非常零的正值,例如[1e10, 1e10+1, 1e10+2]),只需将索引偏移到count_array中的最小值即可。输入:

def counting_sort(unsorted):
   result = [0] * len(unsorted)
   low = min(unsorted)      # we don't care if this is positive or negative any more!
   high = max(unsorted)
   count_array = [0 for i in range(low, high+1)]
   for i in unsorted:
      count_array[i-low] += 1             # use an offset index
   for j in range(1, len(count_array)):
      count_array[j] += count_array[j-1]
   for k in reversed(unsorted):
      result[count_array[k-low] - 1] = k  # here too
      count_array[k-low] -= 1             # and here
   return result 

答案 1 :(得分:0)

当您使用负元素对count_array编制索引时,您的算法无法正常工作。 Python会将count_array[-1]解释为count_array

的最后一个元素

因此,您可以更改代码以将其考虑在内或在排序之前移动所有元素

unsorted = [e - low for e in unsorted]

并最终改回来

result = [e + low for e in result]