This post shows how to implement Binary Search in Python — an efficient algorithm for finding a value in a sorted list, and one of the most frequently asked interview algorithms.
Binary search in Python:
Explanation:
Binary search repeatedly checks the middle element of the list. If the target is smaller, it searches the left half; if larger, the right half. This halves the search space each step, making it far faster than checking every element one by one.
Python Program for Binary Search
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
numbers = [11, 12, 22, 25, 34, 64, 90]
target = 25
result = binary_search(numbers, target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
Output:
Element found at index 3
Binary search shows up constantly in interviews — practice more problems like this with our Problem of the Day.
