Binary search
Find a value in a sorted array by repeatedly halving the range that could contain it: at most about 20 comparisons for a million items.
Description
Binary search finds a target in a sorted array without looking at most of it. It keeps a range, from lo to hi, where the target could be. Each step looks at the middle element: if it's the target, done; if it's smaller, the target must be in the right half; if it's larger, in the left half. Each comparison halves the range.
Halving is powerful. A million items need at most 20 comparisons; a billion need 30. A linear scan of the same billion items would need, on average, half a billion.
The idea goes far beyond finding exact values. The same halving works for any question with a yes/no answer that flips once across a sorted range: the first position where a value could be inserted, the first version where a test started failing (git bisect), or the smallest capacity that satisfies a requirement.
How it works
Searching for 43 in a sorted array: lo, mid and hi
- index 0: 3
- index 1: 9
- index 2: 10
- index 3: 27
- index 4: 38
- index 5: 43
- index 6: 55
- index 7: 82
- index 8: 90
- index 9: 97
Step through: find 43
Step 1 of 4Search for 43 in 10 sorted values.
Complexity
| Operation | Average | Worst |
|---|---|---|
| Search a sorted array | O(log n) | O(log n) |
| Best caseThe target is the first middle element. | O(1) | O(1) |
| Sort first, then search onceOnly worth it if you search many times. | O(n log n) | O(n log n) |
Space: O(1) iterative; O(log n) recursive
Binary search needs random access in O(1), so it works on arrays, not linked lists. For data that changes often, keep it in a balanced search tree instead of re-sorting an array.
TypeScript implementation
Iterative binary search for an exact match, plus lowerBound: the first index where a value could be inserted while keeping the array sorted.
// Binary search on a sorted array. Both functions keep the invariant that the
// answer is inside [lo, hi] and halve that range every step.
/** Index of target, or -1 if it isn't present. */
export function binarySearch(sorted: number[], target: number): number {
let lo = 0;
let hi = sorted.length - 1;
while (lo <= hi) {
const mid = lo + Math.floor((hi - lo) / 2); // avoids overflow in fixed-size integer languages
if (sorted[mid] === target) return mid;
if (sorted[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
/** First index whose value is ≥ target: where target would be inserted. */
export function lowerBound(sorted: number[], target: number): number {
let lo = 0;
let hi = sorted.length; // note: hi is exclusive here
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (sorted[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
export function demo(): string[] {
const a = [3, 9, 10, 27, 38, 43, 55, 82, 90, 97];
const lines = [
`find 43 → index ${binarySearch(a, 43)}`,
`find 50 → ${binarySearch(a, 50)} (not present)`,
`insert 50 at index ${lowerBound(a, 50)} to keep the array sorted`,
];
// How few steps a million items need:
const million = Array.from({ length: 1_000_000 }, (_, i) => i * 2);
let steps = 0, lo = 0, hi = million.length - 1;
const target = 1_234_566;
while (lo <= hi) {
steps++;
const mid = lo + Math.floor((hi - lo) / 2);
if (million[mid] === target) break;
if (million[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
lines.push(`found ${target} among a million values in ${steps} steps`);
return lines;
}When to use it
Use it when
- The data is sorted and supports fast access by index.
- You search the same data many times, so sorting once pays off.
- You need the insertion point, or the first or last element satisfying a condition.
- Any monotone yes/no question over a range: version bisection, capacity planning, numeric answers.
Avoid it when
- The data isn't sorted and you search only once: a linear scan, O(n), beats sorting, O(n log n).
- You need lookups by exact key with frequent inserts: a hash table gives O(1) on average.
- The data is in a linked list without random access.
Pitfalls
- Integer overflow in
(lo + hi) / 2in languages with fixed-size integers. Uselo + (hi - lo) / 2. - Off-by-one loops: mixing
lo <= hiwithhi = mid(instead ofmid - 1) can loop forever. - Unsorted input, which gives wrong answers silently.
- Duplicates: plain binary search returns an index of the value, not necessarily the first. Use a lower-bound search for the first.
Alternatives
Hash table
Choose it when you only need exact-key lookups, with frequent inserts and deletes.
Balanced search tree
Choose it when the data changes often and must stay ordered.
Two pointers
Choose it when you're looking for pairs in a sorted array, such as two values that sum to a target.