简体   繁体   中英

QuickSort using in place sorting

I am trying to write quicksort code in python using in place sorting. My code works perfect in sub arrays however It seems like it can not stick the subarrays together to make the final sorted array.

def quickSort (ar):

    if len(ar)>1:
        pivot = ar[-1]
        wall = 0
        for i in range(len(ar)-2):
            if ar[i] <= pivot:
                ar[wall], ar[i] = ar[i], ar[wall]
                wall += 1
        ar[wall], ar[-1] = ar[-1], ar[wall]
        quickSort (ar[:wall])
        quickSort (ar[wall+1:])

Your code is trying to sort in-place—but then it's passing down sliced copies to the recursive calls, so you're just sorting those copies in-place and then discarding them.

(If that isn't clear: slicing a list always copies the list. More complicated types—like memoryview or np.array —may support "shared views" over part of their structure, but list is deliberately simple.)


One way to solve this is to change to a copying rather than in-place sort, which can end with:

return quickSort(ar[:wall]) + ar[wall] + quickSort(ar[wall+1:])

(Of course you also need to change the trivial code above that to build a copy instead of shuffling in-place.)


The other way is to keep doing it in-place by passing down the list itself and slice indexes, rather than a sliced copy of the list:

def quickSort(ar, start=None, stop=None):
    if start is None: start = 0
    if stop is None: stop = len(ar)

    pivot = ar[stop-1]
    for i in range(start, (stop-start)-2):

    # and so on

    quickSort(ar, start, wall)
    quickSort(ar, wall+1, stop)

Just make sure you pick one or the other—a sort that's partly in-place and partly copying-and-assembling is a big mess.

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