有人知道为什么我的快速排序出现以下递归错误吗?不知道为什么我收到“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/