• A binary search is an algorithm that is used to find the position of an element in an ordered list.
• We can perform binary search operation in two ways like without recursion(iterative method) and with recursion.
• A binary search is an efficient technique of searching through a list of data items, it is more efficient than a linear search because it cuts down the search to half.
In Python binary search we will give a sorted list and we will find the element by using the binary search. In an iterative method, we will loop through every item in our list, find the middle value, and continue to do till the search complete.
def binary_searchiter(list1, n): low = 0 high = len(list1) - 1 mid = 0 while low <= high: mid = (high + low) // 2 if list1[mid] < n: low = mid + 1 elif list1[mid] > n: high = mid - 1 else: return mid return -1 list1 = [10,20,30,40,50,60] n = 30 r = binary_searchiter(list1, n) if r != -1: print("Element found at index", str(r)) else: print("Element not present in list")
Element found at index 2
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc