So I'm trying recursion for the first time, writing a simple binary search algorithm in Python 3. After running my program I was getting this error: maximum recursion depth exceeded while calling a Python object
I did some research and it said to add this line: sys.setrecursionlimit(40000)
Which I did. When I enter a number that's not in my list I get this Segmentation Fault error. I read this post From what I gather in Python deep recursion exhausts the memory?
I can't imagine deep recursion is not supported in Python? Anyways, here's my code:
import sys
arr = [5, 17, 23, 33, 39, 44, 58, 62, 70, 74, 82, 99]
end = len(arr)
sys.setrecursionlimit(40000)
def binarySearch(arr, start, end, x):
#print("This is end: {}".format(end))
mid = int((end + start)/2)
#print("This is start {}".format(start))
#print("This is end {}".format(end))
#print("This is mid {}".format(mid))
if x == arr[mid]:
return x
elif (x < arr[mid]):
start = 0
end = mid - 1
return binarySearch(arr, start, end, x)
else: # if x > arr[mid]
start = mid + 1
end = end
return binarySearch(arr, start, end, x)
position = binarySearch(arr, 0, 12, 55)
print(position)
xnot being inarr. What would you expect it to return in that case? (Also, you should probably be returningmidnotx)start = 0is one of them. Another is that you don't check for the base casestart > end.