Before going to the program first let us understand what is a Binary Search?
Binary search is a searching technique used to quickly search the element from the given sorted array list. If the element to be searched is found then its position is printed.
To find the element from the unsorted array using Binary Search,
- First Sort the given unsorted array using some sorting techniques like selection sort, quick sort, etc.
- Then use the Binary Search algorithm to find the given element from the array list.
Related: Python Program for Selection Sort
Program code for Binary Search in Python:
# Python Program for Binary Search array =  element_found = False size = int(input("Enter the size of an array: ")) for i in range(size): elements = int(input("Enter the element in ascending order: ")) array.append(elements) element = int(input("Enter the element to be searched: ")) low = 0 high = size - 1 while low <= high: mid = ( low + high ) // 2 if element == array[mid]: element_found = True break elif element < array[mid]: high = mid - 1 else: low = mid + 1 if element_found: print("The element is found and its position is: ", mid + 1) else: print("The element is not found")