Algorithms / Binary search

Binary search

Guess the middle, throw away the half that can’t hold the answer, repeat. Fifteen numbers, three probes, and why it barely slows down at a million.

Beginner7 steps~5 min
lo & hi — edges of the range still in play
mid — the probe, always the middle cell
Target — the value we are hunting for
// THE SHORT VERSION

In 30 seconds

Binary search finds a value in a sorted list by checking the middle item first.

If the middle is too small, the answer can only be to its right; if it is too big, only to its left. Either way, half of what was left is thrown away without being looked at.

That halving is why it is fast: 15 items need at most 4 checks, and a million need 20. The one condition is that the list is already sorted.

Binary search, step by step

STEPS01 / 07
TRY YOUR OWN

Any whole number from 1 to 99. Try 50: it is not in the list.

Indices start at 0. mid rounds down, so with an even range it picks the left of the two middle cells.

STEP 01 / 07 A sorted list
a = [3, 8, 12, … 72, 88] n = 15 target = 47
  1. Step 1: A sorted list. Binary search only works on sorted data. Sorting is what lets a single comparison tell you which half the answer must be in.
  2. Step 2: Set lo and hi. lo and hi mark the part of the list where the target could still be. At the start that is everything.
  3. Step 3: Probe 1: too small. 38 is smaller than 47, and everything left of it is smaller still. 8 cells are ruled out with one comparison.
  4. Step 4: Probe 2: too big. Now the middle of what is left is 59, which overshoots. Everything right of it is bigger, so hi jumps below it.
  5. Step 5: Probe 3: found. The middle of the 3 cells still in play is the target itself. 3 comparisons instead of the 10 a left-to-right scan would need.
  6. Step 6: When it isn’t there. If the target is missing, lo and hi eventually cross. The search stops, and lo is exactly where the value would be inserted. Set the target to 50 to watch it happen.
  7. Step 7: Why it scales. Each probe halves what is left, so doubling the list costs one extra probe. A linear scan’s cost doubles instead.
VALUES SO FAR
n15input
target47input
range····lo · hi
probe 1····go right
probe 2····go left
probe 3····found
50?····missing
n = 10⁶····log n
// DEEP DIVE

The questions people ask

What is the time complexity of binary search?

O(log n). Every comparison halves the range, so a list of n items is exhausted after at most ⌊log₂ n⌋ + 1 comparisons: 4 for 15 items, 10 for 1 000, 20 for a million.

The best case is O(1), when the first middle item happens to be the target. The average case is still O(log n), about one comparison fewer than the worst. The loop version needs O(1) extra memory; a recursive version uses O(log n) stack frames.

Why does binary search only work on a sorted array?

Because the whole method rests on one inference: “this item is too small, so everything before it is too small as well.” That is only true when the items are in order. On unsorted data a comparison tells you about one item and nothing about its neighbours, so nothing can be thrown away.

If the data is not sorted and you only search it once, a linear scan (O(n)) is cheaper than sorting first (O(n log n)). Sorting pays off when the same list is searched many times.

What is the difference between binary search and linear search?

A linear search checks items one after another from the start; it works on any list and takes up to n checks. Binary search jumps to the middle and halves the range each time; it needs sorted data and random access, and takes about log₂ n checks.

For a handful of items the two are equally quick, and a linear scan is simpler. The gap opens fast: at a million items it is 20 checks against as many as a million.

Why is mid sometimes written as lo + (hi − lo) / 2?

In languages with fixed-size integers, lo + hi can overflow when both are large, producing a negative index. lo + (hi − lo) / 2 gives the same middle without ever exceeding hi.

This is not a theoretical worry: a bug of exactly this kind sat in the binary search of Java’s standard library for years before it was reported in 2006. Python integers do not overflow, so there (lo + hi) // 2 is fine.

What does binary search return if the value is not found?

The loop ends when lo has moved past hi. The simple version returns −1 (or “not found”). But lo now points at the first item larger than the target, which is exactly where the target would be inserted to keep the list sorted.

Library versions expose that: Python’s bisect_left and C++’s lower_bound return the insertion point instead of a yes or no. The same variants decide what happens with duplicates, by returning the first matching position rather than whichever one the probes land on.

Can you use binary search on a linked list?

Not usefully. Binary search needs to jump to the middle in one step, and a linked list can only be walked node by node, so each “jump” costs O(n) and the advantage is gone.

When data must stay sorted and change often, a balanced search tree or a skip list gives the same halving idea with cheap inserts.

Spotted a mistake on this page?