Binary Search in Python
Here you will get the example code of Binary Search in Python programming language. To write a python program Binary search we will be using “binary_search” user defined function.
Binary Search is an algorithm used for searching a particular element in an array. It works on sorted array. It is more efficient than linear search as it reduces the number of comparisons to half.
Example of Binary Search in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | # Binary search algorithm def binary_search(arr, target): # Set the start point start = 0 # Set the end point end = len(arr) - 1 while start <= end: mid = (start + end) // 2 if arr[mid] == target: return mid elif arr[mid] < target: start = mid + 1 else: end = mid - 1 # If the element is not present return -1 arr = [] print("Enter 5 numbers ") for i in range(5): item = input('Input item : ') arr.append(item) target = input("Enter a number to search location : ") # Function call result = binary_search(arr, target) if result != -1: print("Element is present at index %d" % result) else: print("Element is not present in array") |
Output
Enter 5 numbers
Input item : 6
Input item : 1
Input item : 3
Input item : 2
Input item : 6
Enter a number to search location : 3
Element is present at index 2
Check out our other Python programming examples