Binary search finds a target in a sorted array by exploiting order: compare the target with the middle element. Either you found it, or you know exactly which half it must be in, and the other half is dead. Repeat on the surviving half. Each step halves the search space, so a million elements take at most ~20 comparisons. That's O(log n), and it is the single most important efficiency jump in this course.
The whole algorithm lives on one invariant: at every moment, if the target exists, it lies within array[low..high]. Everything outside is provably eliminated. Every bug in binary search is a violation of this invariant, a boundary set one too wide (infinite loop) or one too narrow (missed the target). Keep the invariant in your head and the code writes itself.
Implementation
// Returns AN index of target (any one if duplicated), or -1 if absent.
// REQUIRES: arr sorted ascending. Behavior on unsorted input is meaningless.
function binarySearch(arr, target) {
let low = 0;
let high = arr.length - 1;
while (low <= high) { // invariant: target ∈ arr[low..high] (if present)
const mid = low + Math.floor((high - low) / 2); // avoids overflow; === ⌊(low+high)/2⌋
if (arr[mid] === target) return mid;
if (arr[mid] < target) low = mid + 1; // target can only be right of mid
else high = mid - 1; // target can only be left of mid
}
return -1; // low > high → window empty → absent
}Worked example: search 9 in [1, 3, 5, 7, 9, 11]
- 1
Window [0..5], mid 2
arr[2] = 5 < 9 → target is right of mid. low = 3. Indices 0–2 eliminated.
- 2
Window [3..5], mid 4
arr[4] = 9 = target → found at index 4. Two comparisons instead of five.
- 3
Scale it up
For n = 1,000,000: worst case ⌈log₂(n+1)⌉ = 20 comparisons. For n = 2,000,000: 21. Doubling the data adds ONE step, that's logarithmic.
| Operation / case | Cost | Notes |
|---|---|---|
| Best case | O(1) | target is the first mid |
| Average & worst case | O(log n) | ≈ log₂(n) halvings |
| Space (iterative) | O(1) | three variables |
| Space (recursive) | O(log n) | call stack depth |
| Precondition | sorted input | O(n log n) to sort first, worth it for many searches |
Duplicates and boundaries
With duplicates, plain binary search returns some matching index, not necessarily the first or last. When you need boundaries ("leftmost 2", "how many elements < x"), you use a variant that keeps searching after a match: when arr[mid] === target, record mid and keep narrowing left (or right). These lower/upper bound variants power library functions and "first bad version"-style problems.
Binary search also applies beyond arrays: any monotonic predicate (true...true...false...false) can be binary-searched, minimum capacity that works, smallest valid speed, first failing commit. The skill transfers: define the invariant, halve, maintain the invariant.
Practice
Sorted array [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] (indices 0–9). Search for 23. What is the FIRST mid index checked, and the comparison result?
Reveal explanation
mid = ⌊(0+9)/2⌋ = 4, arr[4] = 16 < 23 → search right, low = 5. Then mid = ⌊(5+9)/2⌋ = 7, arr[7] = 56 > 23 → high = 6. Then mid = 5: found. Three comparisons instead of six.