Intuition
Think of guessing a number between 1 and 100 when someone tells you “higher” or “lower.” The smart first guess is 50: whatever the answer, half the numbers are gone. Then 25 or 75, and so on. You never need more than 7 guesses.
Binary search plays that game on a sorted list. Each check halves the part that could still hold the target, so a million values need at most 20 checks.
How it works
- Keep two indexes:
loat the start andhiat the end. The target, if it’s there, is between them. - Look at the middle index,
mid. - If
a[mid]is the target, you’re done. - If
a[mid]is smaller, the target can only be to the right: movelotomid + 1. - If it’s larger, the target can only be to the left: move
hitomid - 1. - When
lopasseshi, nothing is left to check: the target isn’t there.
Complexity
| Case | Checks | When it happens |
|---|---|---|
| Best | 1 | The target is exactly in the middle. |
| Worst | ⌊log₂ n⌋ + 1 | The target is missing, or found on the last check. |
Linear search on the same list may need n checks. For n = 1,000,000 that’s a million against twenty.
Common mistakes
- Searching unsorted data. The halving step assumes order. On unsorted input binary search returns wrong answers without any error.
- Off-by-one loops. With an inclusive
hi, the loop condition must belo <= hi, and the moves must bemid + 1andmid - 1. Mixing styles loops forever or skips values. - Overflow in
lo + hi. See the margin note. - Sorting just to search once. Sorting costs O(n log n). For a single lookup, a linear scan is cheaper.
In other languages
| Language | Built-in |
|---|---|
| Python | bisect.bisect_left(a, x) |
| JavaScript | None built in |
| Java | Arrays.binarySearch(a, x), Collections.binarySearch |
| C | bsearch() |
| Go | slices.BinarySearch(a, x), sort.SearchInts |
| Rust | a.binary_search(&x) |
Check yourself
Check yourself
At most how many checks does binary search need for 1,000 sorted values?
2¹⁰ = 1,024 is the first power of two above 1,000, so at most ⌊log₂ 1000⌋ + 1 = 10 checks.
Check yourself
Can you binary search [4, 1, 9, 7] for 9?
Ruling out a half only works on sorted data. Here it happens to find 9, but searching for 4 fails: the first check sees 1, decides 4 must be to the right, and never looks at index 0.
Sources
- Donald Knuth, The Art of Computer Programming, Vol. 3, section 6.2.1.
- Joshua Bloch, “Extra, Extra – Read All About It: Nearly All Binary Searches and Mergesorts are Broken,” Google Research Blog, 2006.
Finished this page?
Your list