I implemented a recursive way of binary search and I'm facing a problem. Ths is my code:
def foo(x, ls):
left, right = 0, len(ls)-1
def search(l, r):
if l>r:
return False
mid = (l+r)//2
if x < ls[mid]:
return search(l,mid-1)
elif x > ls[mid]:
return search(mid+1,r)
else:
return True
return search(left,right)
this function works fine. However if I remove the return
from the if statements, and call search function without a return
, it raises wrong answers. Can anyone explain this? What is the exact difference?