I know it could be duplicated, but haven't figured out which part of my code causes recursion error. It should use less than 1000 stacks which is the recursion limit in Python.
import random
def quick_sort(arr):
# if array is empty or has only 1 element
# it means the array is already sorted, so return it.
if len(arr) < 2:
return arr
else:
rand_index = random.randint(0,len(arr)-1)
pivot = arr[rand_index]
less = []
greater = []
# create less and greater array comparing with pivot
for i in arr:
if i <= pivot:
less.append(i)
else:
greater.append(i)
return quick_sort(less) + [pivot] + quick_sort(greater)
if __name__ == "__main__":
sample_array = [6,3,7,2,7,4,7,3,21,54,0,6,5,3,1,3]
sorted_array = quick_sort(sample_array)
print(sorted_array)
The error code is here below:
File "quick_sort.py", line 24, in <module>
sorted_array = quick_sort(sample_array)
File "quick_sort.py", line 20, in quick_sort
return quick_sort(less) + [pivot] + quick_sort(greater)
File "quick_sort.py", line 20, in quick_sort
return quick_sort(less) + [pivot] + quick_sort(greater)
File "quick_sort.py", line 20, in quick_sort
return quick_sort(less) + [pivot] + quick_sort(greater)
[Previous line repeated 991 more times]
File "quick_sort.py", line 9, in quick_sort
rand_index = random.randint(0,len(arr)-1)
File "C:\Program Files (x86)\Python36-32\lib\random.py", line 221, in randint
return self.randrange(a, b+1)
File "C:\Program Files (x86)\Python36-32\lib\random.py", line 197, in randrange
return istart + self._randbelow(width)
File "C:\Program Files (x86)\Python36-32\lib\random.py", line 231, in _randbelow
if type(random) is BuiltinMethod or type(getrandbits) is Method:
RecursionError: maximum recursion depth exceeded while calling a Python object
Your help would be very appreciated. Thanks!
i <= pivotThis condition!! When you iterate over arr, you includepivotas well. So your end result array will have more elements than the original array.