Binary Search is a highly efficient searching algorithm. It works by repeatedly dividing the search interval in half. A key requirement for binary search is that the input list must be sorted.
Compared to Linear Search (O(n)), Binary Search is much faster, with a time complexity of O(log n).
Imagine you're looking for a word in a dictionary. You don't start at the first page; you open it roughly to the middle. If your word comes before the words on that page, you know to look in the first half. If it comes after, you look in the second half. You repeat this process, halving the search area each time, until you find the word.
The algorithm follows these steps:
Here is an iterative implementation of the binary search algorithm.
def binary_search(data, target):
"""
Performs binary search on a sorted list.
Returns the index of the target if found, otherwise returns -1.
"""
low = 0
high = len(data) - 1
while low <= high:
mid = (low + high) // 2 // Find the middle index
// Check if target is present at mid
if data[mid] == target:
return mid
// If target is greater, ignore left half
elif data[mid] < target:
low = mid + 1
// If target is smaller, ignore right half
else:
high = mid - 1
return -1 // Target not found
// --- Usage ---
// The list MUST be sorted
my_list = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
target_value = 23
result = binary_search(my_list, target_value)
if result != -1:
print(f"Element {target_value} is present at index {result}")
else:
print(f"Element {target_value} is not present in the list")
Logarithmic Power: The power of O(log n) is staggering. To search a list of 1 million items, linear search might take up to 1 million comparisons. Binary search would take at most 20!
What is the main prerequisite for performing a binary search?