如何在快速排序程序中实现递归调用



我正在尝试实现递归调用以运行快速排序算法。但是,它似乎不起作用。下面的代码可能有什么问题?显然,网上有可用的解决方案,但是,我想看看我在编写的代码中做错了什么。这将帮助我更好地理解如何使用递归调用。

代码能够使用最后一个索引"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)

最新更新