简体   繁体   English

使用python的合并排序功能中的RunTimeError

[英]RunTimeError in merge sort function using python

I am trying to write a merge sort function using python 2 but i get a RunTimeError 我正在尝试使用python 2编写合并排序功能,但出现RunTimeError

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

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

My code is shown below: 我的代码如下所示:

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)

The RunTimeError is: maximum recursion depth exceeded . RunTimeError为: maximum recursion depth exceeded Does anybody know the cause of this error? 有人知道此错误的原因吗?

You're comparing list values to list indices: 您正在将列表值与列表索引进行比较:

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

Change this to if i <= array[len(array)/2]: and it should work. 更改为if i <= array[len(array)/2]:它应该工作。

This code works: 此代码有效:

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)

There was more than one error. 有多个错误。 You can compare it with your code. 您可以将其与您的代码进行比较。 Hope it help. 希望对您有所帮助。 Major error was in this line: 主要错误在这一行:

if i < len(array)/2 which led right to be empty when len(array)==2 which caused the error. if i < len(array)/2导致len(array)==2导致错误,则导致right为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM