def binary_search(array,key,left,right):
if left>right:
return -1
mid=(right+left)//2
if key==array[mid]:
return mid
i=0
if key<array[mid]:
i+=1
print("subarray at step {} : {}".format(i,array[left:mid]))
return binary_search(array,key,left,mid-1)
elif key>array[mid]:
i+=1
print("subarray at step {} : {}".format(i,array[mid:right]))
return binary_search(array,key,mid+1,right)
array=[1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,77,88,99,222,333]
res= binary_search(array,88,0,len(array))
print(res if res!=-1 else "Not found")
In this binary search code, I couldn't figure out why the counter wan not working. Each time the i
is printed a 1. The counter doesn't increase. What am I doing wrong?
Thank you.
i = 0each time before incrementing it...ialways starts as0for the section.