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 is being printed as 1 because you are i is being set to 0 inside binary_search function on each call. try moving out initiaization of i outside the function.
def binary_search(array,key,left,right):
global i
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)
i =0
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))
You need to change the scope of variable i to make it global.
make i as global variable and to assing valuable call global keywoard
i = 0
def binary_search(array,key,left,right):
if left>right:
return -1
mid=(right+left)//2
# i=0
if key==array[mid]:
return f'it found position {mid}'
if key<array[mid]:
global i
i = 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(len(array))
print(res if res!=-1 else "Not found")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.