Unexpected behavior of binary search algorithm in python -
i new python. while trying make binary search function , facing , unexpected problem. don't understand why happening. tried modify code, result same every time. here 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 type in shell , 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. doesn't search element in list.
the mistake right here:
if((first-last)<2): #this less 2
should be:
if((last-first)<2):
Comments
Post a Comment