Binary Search
def bin_search_recursive(a, k, l, h):
mid = (l+h)//2
if k==a[mid]:
return mid
elif k<a[mid]:
return bin_search_recursive(a, k, l, mid-1)
else:
return bin_search_recursive(a, k, mid+1, h)
def bin_search_call(a, k):
return bin_search_recursive(a, k, 0, len(a))
a = [int(x) for x in input("Enter array a: ").strip().split()]
k = int(input("Enter key k: "))
try:
print("%d found at index %d" %(k, bin_search_call(a, k)))
except:
print("Element not found!")Last updated