Skip to main content
Intermediate ~16 min read

Binary Search

Halve the search space every step: the classic O(log n) algorithm, its invariants, and its boundary traps.

Prerequisites: Linear Search, Big O Notation & Time Complexity

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

binary-search.js
// 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. 1

    Window [0..5], mid 2

    arr[2] = 5 < 9 → target is right of mid. low = 3. Indices 0–2 eliminated.

  2. 2

    Window [3..5], mid 4

    arr[4] = 9 = target → found at index 4. Two comparisons instead of five.

  3. 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 / caseCostNotes
Best caseO(1)target is the first mid
Average & worst caseO(log n)≈ log₂(n) halvings
Space (iterative)O(1)three variables
Space (recursive)O(log n)call stack depth
Preconditionsorted inputO(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.

Check your understanding

  1. 1.Why does binary search require sorted input?
  2. 2.Worst case comparisons for binary search on a sorted array of 1,000 elements?
  3. 3.In the standard loop, after finding arr[mid] < target, why set low = mid + 1 instead of low = mid?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Visualize it

Binary Search

Play, pause, and scrub the real algorithm step by step.

Play it

Binary Search Challenge

Pick the true midpoint of the search window each round and eliminate half the array. Miss twice and the hint a…

Keep going