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

问题描述 投票:-1回答:1

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

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

python recursion quicksort
1个回答
0
投票

您递归调用quicksort,然后丢弃结果:

    if len(Left)>1:
        quicksort(Left)
    if len(Right)>1:
        quicksort(Right)

    Left.append(pivot)
    combined=Left+Right
    return combined

也许Left = quicksort(Left)

© www.soinside.com 2019 - 2024. All rights reserved.