使用python的合并排序函数中的RunTimeError

时间:2016-07-19 14:36:03

标签: python sorting mergesort

我正在尝试使用python 2编写合并排序函数,但我得到一个RunTimeError

  

输入:未排序列表(例如:[10,9,8,7,6,5,4,3,2,1])

     

产出:[1,2,3,4,5,6,7,8,9,10]

我的代码如下所示:

lst = [10,9,8,7,6,5,4,3,2,1]
def mergesort(array):
if len(array) == 1:
    return array
left = []
right = []
for i in array:
    if i <= len(array)/2:
        left.append(i)
    else:
        right.append(i)
left = mergesort(left)
right = mergesort(right)
return merge(left,right)

def merge(left,right):
    sortedlist= []
    while left and right:
        if left[0]>right[0]:
            sortedlist.append(right[0])
            right.pop(0)
        else:
            sortedlist.append(left[0])
            left.pop(0)
    while left:
        sortedlist.append(left[0])
        left.pop(0)
    while right:
        sortedlist.append(right[0])
        right.pop(0)

    return sortedlist


print mergesort(lst)

RunTimeError是:maximum recursion depth exceeded。有人知道这个错误的原因吗?

2 个答案:

答案 0 :(得分:0)

您将列表值与列表索引进行比较:

for i in array: # i is a list value
    if i <= len(array)/2: # len(array)/2 is a list index

将此更改为if i <= array[len(array)/2]:,它应该有效。

答案 1 :(得分:0)

此代码有效:

lst = [10,9,8,7,6,5,4,3,2,1]

def mergesort(array):
    if len(array) == 1:
        return array
    left = []
    right = []
    for i in range(len(array)):
        if i < len(array)/2:
            left.append(array[i])
        else:
            right.append(array[i])



    left = mergesort(left)
    right = mergesort(right)
    return merge(left,right)

def merge(left,right):
    sortedlist= []
    while left and right:
        if left[0]>right[0]:
            sortedlist.append(right[0])
            right.pop(0)
        else:
            sortedlist.append(left[0])
            left.pop(0)
    while left:
        sortedlist.append(left[0])
        left.pop(0)
    while right:
        sortedlist.append(right[0])
        right.pop(0)

    return sortedlist


print mergesort(lst)

有多个错误。您可以将其与您的代码进行比较。希望它有所帮助。 主要错误在于这一行:

if i < len(array)/2导致right导致错误的len(array)==2时为空。