简体   繁体   English

Python 中的快速排序递归

[英]Quick Sort Recursion in Python

I have been studying the quick sort algorithm below and have not been able to understand why [pivot] needs to be returned in brackets and why it needs to be returned at all.我一直在研究下面的快速排序算法,一直无法理解为什么 [pivot] 需要在括号中返回以及为什么它需要返回。 Doesn't the output of the function just need to run the new arrays(less and greater) through the existing function and then get the pivot value like the first time it was called?函数的输出是否只需要通过现有函数运行新数组(更少和更大),然后像第一次调用时一样获取主元值?

def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    else:
        pivot = arr.pop()

    greater = []
    less = []
    for i in arr:
        if i > pivot:
            greater.append(i)
        else:
            less.append(i)
    return quick_sort(less) + [pivot] + quick_sort(greater)

arr1 = [7,8,9,6,5,4,7,8,9]

quick_sort(arr1)

I have been studying the quick sort algorithm below and have not been able to understand why [pivot] needs to be returned in brackets and why it needs to be returned at all.我一直在研究下面的快速排序算法,却无法理解为什么[pivot]需要放在方括号中,以及为什么它需要全部返回。 Doesn't the output of the function just need to run the new arrays(less and greater) through the existing function and then get the pivot value like the first time it was called?函数的输出不是只需要通过现有函数运行新的数组(更少和更大),然后像第一次调用该函数一样获得透视值吗?

def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    else:
        pivot = arr.pop()

    greater = []
    less = []
    for i in arr:
        if i > pivot:
            greater.append(i)
        else:
            less.append(i)
    return quick_sort(less) + [pivot] + quick_sort(greater)

arr1 = [7,8,9,6,5,4,7,8,9]

quick_sort(arr1)

The solution is trying to merge three arrays into one.解决方案是尝试将三个数组合并为一个。 For example:例如:

mergedArr = [1,2,3]+ [4] + [5,6,7] print(mergedArr) # [1, 2, 3, 4, 5, 6, 7]

Wrapping the pivot inside the bracket will just explicitly turn it into a list so the python program could append everything together将枢轴包裹在括号内只会将其显式转换为列表,以便 python 程序可以将所有内容附加在一起

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM