Python快速排序-在终端上运行的递归错误

标签 python quicksort

有人知道为什么我的快速排序出现以下递归错误吗?不知道为什么我收到“RecursionError:比较中超出最大递归深度”。我问过其他人,他们说我的递归不应超过:

这是代码:

def merge(array, low, mid, high):

i,j,k = low,mid+1,low
leftarray = array[low:mid+1]
rightarray = array[mid+1:high+1]

temp= [0]*high

while i<=mid and j<=high:

    if array[i]<array[j]:
        temp[k] = array[i]
        i+=1
    else:
        temp[k] = array[j]
        j+=1
    k+=1

if i>mid:
    temp[k:high+1] = array[j:high+1]
else:
    temp[k:high+1] = array[i:mid+1]  

array[low:high+1] = temp[low:high+1]

还有错误

(base) b98-aruba1-guest-10-110-7-206:desktop ericadamian$ python Quicksort1.py
RecursionError: maximum recursion depth exceeded in comparison
(base) b98-aruba1-guest-10-110-7-206:desktop ericadamian$

最佳答案

评论中指出的修复。

def Quicksort1(array, low, high):               #fix

    if high > low:
        index = Partition(array, low, high)     #fix
        Quicksort1(array, low, index - 1)       #fix
        Quicksort1(array, index + 1, high)      #fix

def Partition(array, low, high):                #fix

    firstitem = array[low]
    j = low
    for i in range(low+1, high+1):              #fix
        if array[i] < firstitem:
            j+=1
            array[j], array[i] = array[i], array[j]
    index = j
    array[low], array[index] = array[index], array[low]     
    return index                                #fix

array = [10, 3, 4, 8, 1, 7]
Quicksort1(array, 0, len(array)-1)              #fix
for j in range(len(array)):                     #fix
    print ("%d" %array[j])                      #fix

关于Python快速排序-在终端上运行的递归错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58176143/

相关文章:

python - PyQt Qthread自动重启

python - 如何通过 scapy 发送 FIN 数据包关闭连接?

python - 替换 PIL 中的单一颜色?

c++ - 在 C++ 中围绕中位数进行分区的快速排序实现

python - 可变刺激持续时间,但 PsychoPy 中有两种固定 ISI

python - 如果 zeep 中的强制 wsdl 字段为空,如何删除该字段

c++ - STL 排序进入无限循环?

javascript - 这种选择排序的实现有什么问题?

c - 像 C 中的一维数组一样对二维数组进行排序?

C++ 为几乎相同的代码提供不同的输出