我正试图实现递归调用来运行quicksort算法。然而,它似乎没有工作。下面的代码可能有什么问题?显然,网上有很多解决方案,但是,我想看看我写的代码中哪里做错了。这将帮助我更好地理解如何使用递归调用。
该代码能够使用最后的索引 "6 "来做第一个分区
def quicksort(list):
if len(list)>1:
pivot=list[int(len(list)-1)]
Left=[]
Right=[]
i=0
while i<int(len(list)):
if list[i]<pivot:
Left.append(list[i])
elif list[i]>pivot:
Right.append(list[i])
i=i+1
if len(Left)>1:
quicksort(Left)
if len(Right)>1:
quicksort(Right)
Left.append(pivot)
combined=Left+Right
return combined
list=[9, 7, 5, 11, 12, 2, 14, 3, 10, 6]
print(quicksort(list))
输出。 [5, 2, 3, 6, 9, 7, 11, 12, 14, 10]
你调用 quicksort
递归,然后丢弃结果。
if len(Left)>1:
quicksort(Left)
if len(Right)>1:
quicksort(Right)
Left.append(pivot)
combined=Left+Right
return combined
也许 Left = quicksort(Left)
?