Algorithms · Binary search

Binary search

Find a number in a sorted list by halving.

The problem

The numbers are sorted from small to big. Return the position of target, or -1 if it isn’t there.

find([-1, 0, 3, 5, 9, 12], 9)4
find([-1, 0, 3, 5, 9, 12], 2)-1
Binary search. Throw away half. Guess my number from 1 to 100. “Higher!” “Lower!” Seven guesses are always enough.

Start with the way that works

This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.

def find(nums, target):take sorted numbers and a target
for i in range(len(nums)):look at each position, left to right
if nums[i] == target:is this the one?
return ifound it
return -1not there

Now ask: what if there were a billion?

A billion sorted items need only about 30 looks. That’s why databases keep their indexes sorted, and why LevelDB can find one key among billions on a disk.

Aim for O(log n)🌱 warm-up

Think it through

The list is sorted and the middle number is too small. What about everything to its left?

  • Could be anything
  • All too small too
Show the answer

All too small too. Sorted means one look rules out half the list. Throw that half away and look at the middle of what’s left.

Halving each time, how many looks for a million numbers?

  • About 1,000
  • About 20
Show the answer

About 20. A million halves to 1 in about 20 steps (2²⁰ ≈ a million). That’s O(log n): databases, git bisect and dictionaries in your phone all lean on it.

Stuck? 3 nudges, smallest first
  1. The list is sorted. If the middle number is too small, what do you know about everything to its left?
  2. They’re all too small too! Throw that whole half away and look at the middle of what’s left.
  3. Keep lo and hi. While lo <= hi: check mid = (lo + hi) // 2, then move lo = mid + 1 or hi = mid - 1.

The fast way

Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.

Show the fast version
def find(nums, target):take sorted numbers and a target
lo, hi = 0, len(nums) - 1it can only be somewhere from lo to hi
while lo <= hi:while there's anywhere left to look
mid = (lo + hi) // 2look in the middle
if nums[mid] == target:found it?
return midits position
if nums[mid] < target:the middle is too small?
lo = mid + 1throw away the left half
else:the middle is too big
hi = mid - 1throw away the right half
return -1nowhere left: not there

Where it’s used for real

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with binary search