Recursive quicksort only returning result of first recursive call

35 views Asked by At

I'm trying to implement quicksort in Python based on pseudocode I read in class but it does not sort the list. It does the recursion and always returns the result of the first recursive call (which is not sorted). Could anyone explain what I'm doing wrong?

def quick_sort(S):
    n = len(S)
    if n < 2:
        return
    p = S[0]
    L = []
    E = []
    G = []
    for i in range(0,len(S)):
        if S[i] < p:
            L.append(S[i])
        elif p < S[i]:
            G.append(S[i])
        else:
            E.append(S[i])
    quick_sort(L)
    quick_sort(G)
    S=L+E+G
1

There are 1 answers

0
Daniel On

You don't return anything, you only create new lists, but don't use them. Return the new list:

def quick_sort(S):
    n = len(S)
    if n < 2:
        return S
    p = S[0]
    L = []
    E = []
    G = []
    for v in S:
        if v < p:
            L.append(v)
        elif p < v:
            G.append(v)
        else:
            E.append(v)
    return quick_sort(L) + E + quick_sort(G)

print quick_sort([6,4,2,3])