【问题标题】:Python: Quicksort in a recursive wayPython:以递归方式快速排序
【发布时间】:2021-06-26 18:14:03
【问题描述】:

我正在尝试在 python 中实现快速排序。它对子数组进行排序,但是当递归调用返回到前一个阶段时,它再次将它们混合在一起。你能指出我在哪里犯了错误吗?

def quicksort(a):
    if len(a) <= 1:
        return a
    else:
        low = 0
        high = len(a) - 1
        pivot = a[high]
        index = 0

        for item in range(low, high):
            if a[item] <= pivot:
                
                a[item], a[index] = a[index], a[item]
                index += 1
        
        a[index], a[high] = a[high], a[index]

    quicksort(a[:index])
    quicksort(a[index+1:])
    
    return a

提前致谢。

【问题讨论】:

  • 对于递归调用quicksort(a[:index])quicksort(a[index+1:]) 中的返回值,你没有任何事情——因此这些调用没有效果。您可能还想用return a[:] 替换return a,因为您的代码似乎在努力返回一个新的、排序的数组,而不是给定数组的就地排序。
  • @JohnColeman 感谢约翰的帮助。我已经整理好了。
  • @Maciej 随时分享self answer

标签: python algorithm sorting quicksort


【解决方案1】:

@ggorlen - 上述问题的解决方案

def quicksort(a, low, high):
    if low < high:

        pivot = a[high]
        index = low

        for item in range(low, high):
            if a[item] <= pivot:
            
                a[item], a[index] = a[index], a[item]
                index += 1
    
        a[index], a[high] = a[high], a[index]

        quicksort(a, low, index-1)
        quicksort(a,index+1, high)

    return a

【讨论】:

    猜你喜欢
    • 2020-04-18
    • 1970-01-01
    • 2020-08-14
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    相关资源
    最近更新 更多