So I'm writing a recursive binary search algorithim in Python and it's been working great ...... except when I tried a certain number.
I'm working off of a list of 10,000 randomized numbers that have been sorted.
It eventually fails with this error:
RecursionError: maximum recursion depth exceeded while calling a Python object
I've put in counters inside the function to keep track of the low/high points and current search count. When I run bSearch(3333), I get the above error and this weird output...
0 None 1
0 4998 2
0 2498 3
0 1248 4
0 623 5
312 623 6
312 466 7
312 388 8
312 349 9
331 349 10
331 339 11
336 339 12
338 339 13
338 337 14
338 337 15
It just keeps repeating 338 337 until it reaches the cursions ceiling.
Here's my function:
def bSearch(list, value, lowPoint=0, highPoint=None, searchNum=1):
print(lowPoint,highPoint,searchNum)
searchNum += 1
if highPoint is None:
highPoint = len(list) - 1
if lowPoint == highPoint:
if list[lowPoint] == value:
return lowPoint, searchNum
else:
return -1, searchNum
midPoint = (lowPoint + highPoint) // 2
if list[midPoint] > value:
return bSearch(list, value, lowPoint, midPoint - 1, searchNum)
elif list[midPoint] < value:
return bSearch(list, value, midPoint + 1, highPoint, searchNum)
else:
return midPoint