Posts

Showing posts with the label binary search

Binary Search Algorithm in Python

Binary Search has less time complexity as compared to linear search. In linear search, potentially all the members are checked while in binary search case, chunks of data are dropped where the target element is not there according to the conditions in the program. def binarySearch(mylist, target): start = 0 # index of 1st element in list end = len(mylist)-1 # index of last element in list step = 0 # binary search operation step while start<=end: if target not in mylist: print(f"Sorry the value {target} is not found in the list.") return print("At step:",step,"The list is",mylist[start:end+1]) step += 1 middle = (start + end) // 2 if target == mylist[middle]: print(f"Your target value which is {target} is found in the list at index {middle}") return elif target < mylist[middle]: