AP® Computer Science Principles · Big Idea 3 · Topic 3.11

Binary Search: Halving the Search Space

Binary search finds a target in a sorted list by repeatedly checking the middle value and throwing away the half that can't contain the target, cutting the remaining data in half each time.

Searching a sorted list, you don't need to check every item one by one. Look at the middle item instead. If it matches, you're done. If the target is smaller, everything to the right of the middle is too big to matter, so throw it all away in one move. If the target is bigger, throw away everything to the left. Either way, one comparison eliminates half the remaining list. That's the whole trick: sorted order lets you make a decision about an entire half without checking each item in it.

This is why binary search beats checking items from one end: a linear search might need to look at every single item, but binary search needs only about log base 2 of n comparisons. A list of a million sorted items takes at most about 20 comparisons, not a million. Each round the problem size shrinks by half, so the work shrinks fast even as the list grows huge.

Binary search sits next to linear search as the course's go-to contrast for runtime: linear search works on any list but scales poorly, binary search scales beautifully but demands sorted data first. That tradeoff connects forward to the idea of algorithmic efficiency and why some problems need preprocessing, like sorting, before a faster algorithm becomes possible at all.

Key terms

binary search
An algorithm that finds a target in a sorted list by repeatedly checking the middle item and discarding half the remaining items.
sorted list
A list whose items are arranged in increasing or decreasing order, required for binary search to work correctly.
linear search
An algorithm that checks each item in order until it finds the target, working on any list but slower on average.
search space
The portion of the list still being considered as a possible location for the target.

Watch it explained

  1. How it worksHow does each comparison in a binary search throw away half of the remaining data?
  2. Worked exampleTrace a binary search for 37 in the sorted list 3, 8, 15, 22, 37, 44, 51, 60, 78.
  3. Worked exampleTrace a binary search for 5 in the sorted list 1, 3, 5, 7, 9, 11, 13 and count how many comparisons it takes.
  4. Common mistakeWhy doesn't binary search work on a list that has not been put in sorted order?
  5. Going furtherWhat changes about the search when the value being looked for is not in the list?

Check yourself

Your turn1 of 2
A binary search starts with 140 items remaining to check, where n is chosen so it divides evenly. After one comparison, half of them are eliminated. How many items remain after just this one comparison?

End of topic.