I’m trying to implement an in-place Quick Sort in Python. I have two slightly different versions of my partitioning logic, and I’m confused because both seem correct on small arrays, but the second version can cause RecursionError: maximum recursion depth exceeded
Here are the two versions:
def quick_sort_safe(arr, low, high):
if low < high:
pivot = arr[high]
p = low - 1
for i in range(low, high):
if arr[i] <= pivot:
p += 1
arr[i], arr[p] = arr[p], arr[i]
arr[high], arr[p+1] = arr[p+1], arr[high]
pivot_index = p + 1
quick_sort_safe(arr, low, pivot_index-1)
quick_sort_safe(arr, pivot_index+1, high)
def quick_sort_overflow(arr, low, high):
if low < high:
pivot = arr[high]
p = low
for i in range(low, high):
if arr[i] <= pivot:
arr[i], arr[p] = arr[p], arr[i]
p += 1
arr[high], arr[p] = arr[p], arr[high]
pivot_index = p
quick_sort_overflow(arr, low, pivot_index-1)
quick_sort_overflow(arr, pivot_index+1, high)
Problem description: this is the error i'm getting: ->RecursionError: maximum recursion depth exceeded there is not such error like indexOutOfRange
The difference between this two functions is just how i calculate the position of the pivot, and when i debug it on very big array, the second one give me an recursion error. from what i see they should behave the same way