1# This is real binary search
2# this algorithm works very good because it is recursive
3
4def binarySearch(arr, min, max, x):
5 if max >= min:
6 i = int(min + (max - min) / 2) # average
7 if arr[i] == x:
8 return i
9 elif arr[i] < x:
10 return binarySearch(arr, i + 1, max, x)
11 else:
12 return binarySearch(arr, min, i - 1, x)
13
1#grepper
2
3def binary_search(item_list,item):
4 first = 0
5 last = len(item_list)-1
6 found = False
7 while( first<=last and not found):
8 mid = (first + last)//2
9 if item_list[mid] == item :
10 found = True
11 else:
12 if item < item_list[mid]:
13 last = mid - 1
14 else:
15 first = mid + 1
16 return found
1def binary_search(mylist,low,k,key):
2 high = k - 1
3 mid = (low + high)//2
4
5 if mylist[mid]==key:
6 return mid
7 elif key > mylist[mid]:
8 return binary_search(mylist,mid + 1,k ,key)
9 else:
10 return binary_search(mylist,0,mid, key)
11low = 0
12k = int(input("Enter total amount of elements in k : "))
13mylist = [int(input()) for x in range(k)]
14key = int(input("Which element do we have to find: "))
15print(binary_search(mylist,low,k,key))