Binary search

In a sorted array, look at the middle. If it is too small the target must be to the right, if too big to the left. Each look throws away half of what is left.

O(log n)needs sorted inputno extra space
[2, 5, 8, 12, 16, 23, 38, 56, 72, 91]find 23
25812162338567291

Look for 23. Press play or step forward to start.

1function binarySearch(a, target) {2  let lo = 0, hi = a.length - 1;3  while (lo <= hi) {4    const mid = Math.floor((lo + hi) / 2);5    if (a[mid] === target) return mid;6    if (a[mid] < target) lo = mid + 1;7    else hi = mid - 1;8  }9  return -1;10}

Keys: Space play or pause, ← → step. The URL always points at the frame you are on.

What it costs

CaseTimeWhen
best1the target is the first middle
averagelog nany target
worstlog nthe target is missing: about 20 probes for a million items
space1just lo, mid and hi

Where it breaks

  • Unsorted input. The whole method rests on "too small means go right". On unsorted data it skips right past the target and says it is missing.
  • Off-by-one loops. Use lo <= hi and move to mid + 1 or mid - 1. Mixing styles breaks it: lo < hi with hi = mid - 1 can miss the last item, and lo <= hi with hi = mid can loop forever.
  • Duplicates. It returns a matching index, not the first one. Finding the first or last match needs the lower and upper bound variants.