0

maybe I’m the next person who asks how to release quick sort on python correctly. But it’s important for me to know if I wrote this algorithm correctly by reading the pseudocode from the textbook Essential Algorithms: A Practical Approach to Computer Algorithms.

When I run the code, I get this message. RecursionError: maximum recursion depth exceeded in comparison

import random

def quickSort(arr, start, end):
    if start >= end:  # if len(arr) < 2
        return arr
    else:
        divideIndex = partition(arr, start, end)
        quickSort(arr, start, divideIndex - 1)
        quickSort(arr, divideIndex, end)

def partition(arr, head, tail):
    left = head
    right = tail
    pivot = arr[(head + tail) // 2]  # mid

    while right >= left:
        # looking through the array from the left
        while arr[left] <= pivot:
            left = left + 1
        # looking through the array from the right
        while arr[right] > pivot:
            right = right - 1
        # found a couple of elements that can be exchanged.
        if left <= right:
            swap(arr[right], arr[left])
            # move the left and right wall
            left = left + 1
            right = right - 1
    # return one elements if not found a couple
    return left

def swap(arr1, arr2):
    temp = arr1
    arr1 = arr2
    arr2 = temp

# Generator random variables
deck = list(range(50))
random.shuffle(deck)


start = 0
end = len(deck) - 1
print(quickSort(deck, start, end))
2
  • 1
    Python doesn't support tail recursion optimisation so the length of the callstack growth as a function of array size, so you need additional while in quicksort function + make start and end into variables instead of parameters of a function Commented Apr 13, 2020 at 16:06
  • 1
    your swap function isnt working as expected. it does not affect the array at all Commented Apr 13, 2020 at 16:10

1 Answer 1

1

Try this:

def partition(arr,low,high): 
    i = ( low-1 )        
    pivot = arr[high]    

    for j in range(low , high): 


        if   arr[j] <= pivot: 

            i = i+1 
            arr[i],arr[j] = arr[j],arr[i] 

    arr[i+1],arr[high] = arr[high],arr[i+1] 
    return ( i+1 ) 


def quickSort(arr,low,high): 
    if low < high: 

        pi = partition(arr,low,high) 

        quickSort(arr, low, pi-1) 
        quickSort(arr, pi+1, high)
Sign up to request clarification or add additional context in comments.

Comments

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.