I am new to python. While trying to make a binary search function , i am facing and unexpected problem. I don't understand why this is happening. I tried to modify the code, but result is same every time. Here is the code:
def bsearch(s,e,first,last,calls):
print(first,last,calls)
if((first-last)<2):
return (s[first]==e or s[last]==e)
mid = first + int((last-first)/2)
if (s[mid]==e):
return True
if (s[mid]>e):
return bsearch(s,e,first,mid-1,calls+1)
else:
return bsearch(s,e,mid+1,last,calls+1)
def search(s,e):
bsearch(s,e,0,len(s)-1,1)
This is what i type in shell and get as Output:
>>> s=[1,2,3,4,5,6,7,8,9,10,11,12,13,15,16]
>>> search(s,5)
Output:
0 14 1
Thats it. It doesn't search the element in the list.
The Mistake is right here:
Should be: