When mid=0
and tab[mid] < x
, the code gets stuck because BinarySearchRec(tab[mid:], x)
will loop forever with the same inputs: (tab[mid:],x) -> (tab[0:],x) -> (tab,x)
.
As a proof, you can try the following example:
tab = [1]
x = 2
BinarySearchRec(tab, x)
# recursion error raised
The easiest solution is to make sure that the array tab
decreases in size every time you perform recursion:
def BinarySearchRec(tab, x):
mid = len(tab) // 2
if len(tab) == 0:
return False
if tab[mid] > x:
return BinarySearchRec(tab[:mid-1], x)
elif tab[mid] < x:
return BinarySearchRec(tab[mid+1:], x)
else:
return mid
tab = [1]
x = 2
BinarySearchRec(tab, x)
# now it works
In the new code, the tab
array is trimmed using either mid+1
or mid-1
, since we can discard mid
as a solution when tab[mid] != x
. This makes sure that tab
always decreases at least one element in size, and hence the code does not crash. Cheers,