Skip to content
StackDecode
SearchingAnimated

Binary Search

Repeatedly halve a sorted list by comparing with the middle.

Time

O(log n)

Extra space

O(1)

Use it for

Sorted data with random access.

How it works

  1. The list must be sorted. Keep a window [low, high] that could still contain the target.
  2. Look at the middle element.
  3. If it equals the target, done. If the target is smaller, discard the right half; if larger, discard the left half.
  4. Repeat on the smaller window until it is empty.
  5. Each step halves the window, so it takes about log₂ n steps.

Watch it run

Loading animation…