0

I have what should be a simple quicksort implementation, but it's returning a recursion depth exceeded error, and I'm testing it on a list of less than 30 elements. Moreover, my implementation was working on a list of 10,000 a few days ago, and the only thing I changed was moving it from a Class to a global function. Anyone see what may be causing this?

def quickSort(m, left, right):
    if len(m[left:right]) <= 1:
        return m
    pivot = m[left]
    i = left + 1
    j = left + 1
    for j in range(j, right):
        if m[j] <= pivot:
            m[j], m[i] = m[i], m[j]
            i += 1
    m[left], m[i-1] = m[i-1], m[left]
    m = quickSort(m, left, i)
    m = quickSort(m, i, right)
    return m
2
  • 2
    for j in range(j, right): that can't be good (for readability for the very least) Commented Nov 14, 2012 at 17:59
  • Add some print statements and re-run to see how it progress. Commented Nov 14, 2012 at 18:23

1 Answer 1

2

one of your recursive calls is causing the exception(as you may have guessed :-), also note that you sort the list in place so returning the list is not necessary

def quickSort(m, left, right):
    if right - left  <= 1:
        return

    pivot = m[left]
    i = left + 1 
    j = left + 1 
    for j in range(j, right):
        if m[j] <= pivot:
            m[j], m[i] = m[i], m[j]
            i += 1
    m[left], m[i-1] = m[i-1], m[left]
    quickSort(m, left, i-1)
    quickSort(m, i, right)
Sign up to request clarification or add additional context in comments.

1 Comment

Yup, the pivot should be excluded when sorting the sub-list. Good one, I missed it :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.