0

To implement binary search in a list and print the index position of the given value

l=[] f=0 n=int(input("ebter the size")) for i in range (n): l.append(int(input("enter no:"))) print(l) v=int(input("enter value to be seqrched:")) l.sort() global m def binary(l,v): mid=len(l)//2 if (l[mid]==v): f=1 print(mid) return f elif l[mid]>v: return binary(l[:mid],v) else : return binary(l[mid+1:],v) if binary(l,v)==1: print("it is found ") else: print("not found") this is my code but I am not able to print the index value properly .can u correct this mistake

11th Dec 2018, 1:24 PM
Mara
1 Answer
+ 3
Because you are sending in a partial list recursively, you print the index of that list once the value is found. To print the index of the original list, you must maintain the whole list and pass the index range within it to check.
11th Dec 2018, 3:46 PM
John Wells
John Wells - avatar