简体   繁体   English

带有Python的Quicksort算法引发RecursionError

[英]Quicksort algorithm with python raises RecursionError

I've been trying to debug my code for some hours and haven't had a headway with it. 我已经尝试调试我的代码几个小时了,但是还没有取得进展。 I love if anyone could help me, I just started learning algorithms 我喜欢有人能帮助我,我才开始学习算法

def quicksort(arr):
    start = 0
    end = len(arr) - 1
    quick_sort(arr, start, end)


def quick_sort(arr, start, end):
    if start < end:
        pindex = partition(arr, start, end)
        quick_sort(arr, start, pindex)
        quick_sort(arr, pindex+1, end)


def partition(arr, start, end):
    pivot = arr[end]
    i = start
    for j in range(start, end):
        if arr[j]<= pivot:
            arr[i], arr[j] = arr[j], arr[i]
            i += 1
    arr[i], arr[end] = pivot, arr[i]
    return i;

when i run it with quicksort([6,4,5,4,2,43,1,4,532,515,243,3,34,5,12,24,234,45,6,457,5]) 当我使用quicksort([6,4,5,4,2,43,1,4,532,515,243,3,34,5,12,24,234,45,6,457,5])运行它时

I get 我懂了

RecursionError: maximum recursion depth exceeded in comparison RecursionError:比较中超出了最大递归深度

and I'm quite sure I used a base case at the beginning of the quick_sort function 而且我很确定我在quick_sort函数的开头使用了基本情况

Your quicksort and quick_sort routine use, as parameters, the index of the first and of the last item in the sub-array to be sorted. 您的quicksortquick_sort例程将要排序的子数组中第一项和最后一项的索引用作参数。 After you partition the sub-array, you sort two parts. 对子数组进行分区后,对两部分进行排序。 However, you include the pivot element of the partition in the first part in your call quick_sort(arr, start, pindex) . 但是, 在调用quick_sort(arr, start, pindex)的第一部分中包含了分区的枢轴元素 You should leave the pivot element out , so use quick_sort(arr, start, pindex-1) . 您应该忽略数据透视元素 ,因此请使用quick_sort(arr, start, pindex-1)

Give that a try. 试试看。 You have no comments so it is difficult to debug your program. 您没有评论,因此很难调试您的程序。 Your example input is also far too large and difficult to debug easily. 您的示例输入也太大,难以调试。 Try an empty array, then an array with one element, then some arrays with two elements, and so on, to catch your errors. 尝试一个空数组,然后是一个包含一个元素的数组,然后是一些包含两个元素的数组,依此类推,以捕获错误。

With that one change, your program now passes all my tests. 有了这一更改,您的程序即可通过我的所有测试。

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

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