Binary Search
Efficiently find an element in a sorted array by halving the search space at each step.
The Mathematics
Formal definition, invariant, and complexity analysis
Problem Definition
Given a sorted array and a target value , find the index such that , or determine that is not in the array.
Loop Invariant
At every iteration, if exists in , then it must lie within the current search bounds:
The search space halves each step. We compute the midpoint and compare:
If , we found the target.
If , then .
If , then .
Complexity Analysis
Each step does work and halves the search space. This gives the recurrence:
Solving (or by the Master Theorem, case 2 with ):
Comparison with Linear Search
Linear search examines each element: . For , binary search needs at most comparisons vs. up to for linear search.
See It Work
Searching for 23 in a sorted array
Initialize: search for 23 in array of 10 elements. Set lo=0, hi=9.
The Code
Bridge from mathematical formulation to Python implementation
Mathematical Formulation
Initialize the search bounds to cover the entire array
Loop invariant: target must be within current bounds
Compute the midpoint using integer division
If midpoint value equals target, we found it
Target is larger, eliminate the left half
Target is smaller, eliminate the right half
Python Implementation
def binary_search(A, x):
lo, hi = 0, len(A) - 1 # Initialize search bounds
while lo <= hi: # Invariant: x in A[lo..hi]
mid = (lo + hi) // 2 # Compute midpoint
if A[mid] == x:
return mid # Found: return index
elif A[mid] < x:
lo = mid + 1 # Eliminate left half
else:
hi = mid - 1 # Eliminate right half
return -1 # Not found