Binary Search visualization

Halve a sorted search range each step by comparing against the middle.

Requires sorted data. Compare the middle element with the target: if it is smaller, the target can only be on the right; otherwise only on the left. Discard half every time.

A million elements need at most 20 comparisons.

Complexity

Time: best O(1), average O(log n), worst O(log n). Space: O(1). Difficulty: Beginner.

Pseudocode

procedure binarySearch(A, target):
  lo ← 0; hi ← n − 1
  while lo ≤ hi:
    mid ← (lo + hi) / 2
    if A[mid] = target: return mid
    else if A[mid] < target: lo ← mid + 1
    else: hi ← mid − 1
  return −1

More searching algorithms