简体   繁体   中英

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. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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