0
L = [7, 12, 1, -2, 0, 15, 4, 11, 9]


def quicksort(L, low, high):
    if low < high:
        pivot_location = Partition(L, low, high)
        quicksort(L,low, pivot_location)
        quicksort(L,pivot_location + 1, high)
    return L

def Partition(L, low, high):
    pivot = L[low]
    leftwall = low
    for i in range(low + 1, high, 1):
        if L[i] < pivot:
            temp = L[i]
            L[i] = L[leftwall]
            L[leftwall] = temp
            leftwall += 1
    temp = pivot
    pivot = L[leftwall]
    L[leftwall] = temp
    return leftwall

print(quicksort(L, 0, len(L) - 1))

When I run the code it produces the following result: [-2, 0, 1, 4, 7, 11, 12, 15, 9]. One element is at the wrong position. If anyone could tell me where the problem is ?

2
  • 1
    high should be len(L)... And you should split on low,pivot and pivot,high (so not pivot+1). Commented Mar 11, 2017 at 9:53
  • Only change I made and the code worked is len(L) instead of (len(L) - 1). The splitting is correct. Commented Mar 11, 2017 at 10:06

2 Answers 2

1

Here I just show u another simple way to implement Q_Sort in Python:

def q_sort(lst):
    return [] if not lst else q_sort([e for e in lst[1:] if e <= lst[0]]) + [lst[0]] + q_sort([e for e in lst[1:] if e > lst[0]])


L = [7, 12, 1, -2, 0, 15, 4, 11, 9]

print q_sort(L)

and we get:

[-2, 0, 1, 4, 7, 9, 11, 12, 15]

Sign up to request clarification or add additional context in comments.

3 Comments

Note that OP's qsort is modifying the array inplace, this one creates new lists (if lists are very large this might be an issue)
Yeah, I agree, this method just shows the core concept of quick sort including partition. This is not used in project, but can be used to show the magic of Python
Yes, I liked that implementation. It really shows the magic of Python despite the fact that it should be used only for small lists!
1

I just changed this line of code and it worked fine:

quicksort(L, 0, len(L))

instead of

quicksort(L, 0, len(L) - 1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.