AP® Computer Science A · Unit 4 · Topic 4.17

Binary Search: Halving the Range

Binary search finds a target in a sorted list by checking the middle element and throwing away half the remaining range each time, so it needs only about log2(n) comparisons instead of n.

Binary search works because sorted order lets one comparison do the work of many. Check the middle element: if it's the target, you're done. If the target is smaller, every element to the right of the middle is also too big, so the entire right half disappears in one move. If the target is larger, the entire left half disappears. Either way, one comparison kills half the remaining candidates, not just one candidate.

That halving is why binary search scales so well. A million names takes at most about twenty comparisons, because a million halved twenty times shrinks to roughly one. Each comparison multiplies your progress instead of adding to it: going from n items to n/2, then n/4, then n/8 reaches 1 after about log2(n) steps. Linear search, by contrast, checks elements one at a time and in the worst case looks at every single one, so it needs up to n comparisons. For ten items that difference barely matters; for a million items it's the difference between about twenty looks and a million.

The method depends completely on order. The decision to discard a half rests on assuming everything on one side of the middle is smaller and everything on the other side is larger. On unsorted data that assumption can be false, so the discarded half might actually hold the target. This is also why binary search sits next to sorting in this unit: the sort does the expensive work once, and binary search cashes in on it over and over with cheap, fast lookups.

Key terms

binary search
A search algorithm that repeatedly checks the middle of a sorted range and discards the half that cannot contain the target.
worst case
The scenario requiring the maximum number of comparisons, such as when the target is absent or found last.
log2(n)
The number of times n must be halved to reach 1, roughly the number of comparisons binary search needs.
linear search
A search that checks elements one at a time in order, needing up to n comparisons for n items.

Watch it explained

  1. How it worksHow does checking the middle throw away half the remaining range every single time?
  2. Worked exampleTrace binary search for 23 in {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}, marking each middle.
  3. Worked exampleFind how many comparisons binary search needs at most on a sorted list of 64 items.
  4. Common mistakeWhy doesn't binary search work on data that has not been sorted?
  5. Ties togetherHow does binary search compare with linear search as a collection grows to a million?

Check yourself

Your turn1 of 2
Binary search runs on a sorted list of 28 elements, halving the remaining range every comparison. At most how many comparisons does it need in the worst case (until only one element remains to check)?

End of topic.