Python Merge函数数组范围错误?

时间:2013-08-31 18:02:43

标签: python arrays recursion mergesort

我正在尝试合并两个列表但是会出错。有人有想法吗?

以下是我的合并功能。

 def mymerg(container, first_index, mid_index, last_index):
      left_list = container[:mid_index]
      right_list = container[mid_index:]
      i = 0
      j = 0
      for elem in range(first_index, last_index+1, 1):
           if left_list[i] <= right_list[j]:
                container[elem] = left_list[i]
                i = i + 1
           else:
                container[elem] = right_list[j]
                j = j + 1

这是我的排序函数,它在My_Merge_Sort行中生成错误(container,first_index,mid_index)

    def mymgsor(container, first_index, last_index):
            if first_index < last_index:
                    mid_index = len(container)//2
                    mymgsor(container, first_index, mid_index)
                    mymgsor(container, mid_index+1, last_index)
                    mymerg(container, first_index, mid_index, last_index)

如果first_index&lt;我也会收到此错误last_index:RuntimeError:比较时超出了最大递归深度。我的代码出了什么问题?提前谢谢。

当我调用此函数时,我使用mymgsor(sample_list,0,len(sample_list)-1)

1 个答案:

答案 0 :(得分:1)

使用heapq.merge而不是实现自己的。

>>> import heapq
>>> list(heapq.merge([1,3,5], [2,4,6,7,8]))
[1, 2, 3, 4, 5, 6, 7, 8]

使用heapq.merge:

>>> def mymgsor(container, first_index, last_index):
...     if first_index < last_index:
...         mid_index = (last_index+first_index) // 2
...         mymgsor(container, first_index, mid_index)
...         mymgsor(container, mid_index+1, last_index)
...         container[first_index:last_index+1] = heapq.merge(container[first_index:mid_index+1], container[mid_index+1:last_index+1])
...
>>> xs = [5,4,2,3,1]
>>> mymgsor(xs, 0, len(xs)-1)
>>> xs
[1, 2, 3, 4, 5]

RuntimeError的原因:

以下行总是产生相同的值;导致mymgsor的无限递归:

mid_index = len(container)//2

mymerg计算错误。请尝试以下方法:

def mymerg(container, first_index, mid_index, last_index):
    left_list = container[first_index:mid_index+1]   # copy only  first_index .. mid_index
    right_list = container[mid_index+1:last_index+1] # copy only mid_index+1 .. last_index
    i = 0
    j = 0
    for elem in range(first_index, last_index+1, 1):
        if left_list[i] <= right_list[j]:
            container[elem] = left_list[i]
            i += 1
            if i == len(left_list): # no more left
                container[elem+1:last_index+1] = right_list[j:]
                break
        else:
            container[elem] = right_list[j]
            j += 1
            if j == len(right_list): # no more right
                container[elem+1:last_index+1] = left_list[i:]
                break