0
\$\begingroup\$

This code is meant to sort a list of integers in place using quick sort.

I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview.

def quicksort(l):
    quicksort_helper(l, 0, len(l)-1)


def quicksort_helper(l, lo, hi):
    if lo >= hi:
        return

    pivot_ind = partition(l, lo, hi)
    quicksort_helper(l, lo, pivot_ind-1)
    quicksort_helper(l, pivot_ind+1, hi)

def partition(l, lo, hi):
    pivot = l[hi]
    left = lo

    for right in range(lo, hi):
        if l[right] <= pivot:
            swap(l, left, right)
            left += 1
    swap(l, left, hi)

    pivot_ind = left
    return pivot_ind


def swap(l, i, j):
    temp = l[i]
    l[i] = l[j]
    l[j] = temp
\$\endgroup\$
4
\$\begingroup\$

Swapping

def swap(l, i, j):
    temp = l[i]
    l[i] = l[j]
    l[j] = temp

Just do:

l[i], l[j] = l[j], l[i] # (a)

You could abstract this into a swap function like you have done, but I probably wouldn't in this case. Matter of taste. Nevertheless, if you do swap the body definition should consist of (a).

Unnecessary variables.

pivot_ind = left
return pivot_ind

Just return left. Write a comment explaining what left is if you need to.

\$\endgroup\$
  • \$\begingroup\$ Thanks for the feedback. I think using a swap function implemented as you've done sounds good. Removing the unnecessary variable sounds and using a comment sounds like a good idea. Thanks again :) \$\endgroup\$ – cycloidistic Nov 17 '16 at 21:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.