2. Binary Search

Cut the search space in half with every comparison

You have a phone book with a million names. You're looking for "Martinez." Do you start at page one and check every entry? Of course not -- you open it near the middle, see that you're in the L's, and flip forward. In a few more flips, you've found it.

That intuition is binary search: given a sorted collection, you can find any element in O(log n) time by repeatedly halving the search space. It's one of the most fundamental algorithms in computer science -- and one of the easiest to get subtly wrong.

The Core Idea

Binary search works on any sorted sequence. The algorithm maintains two pointers, low and high, that define the current search range. At each step:

  1. Compute the midpoint

    mid = low + Math.floor((high - low) / 2)
    (We avoid (low + high) / 2 to prevent integer overflow in languages with fixed-width integers.)

  2. Compare the middle element to the target

    If arr[mid] == target, we found it -- return mid.
    If arr[mid] < target, the target must be in the right half -- set low = mid + 1.
    If arr[mid] > target, the target must be in the left half -- set high = mid - 1.

  3. Repeat until found or range is empty

    If low > high, the target is not in the array.

A Simple Example

Searching for 23 in [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]

Array: [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
Target: 23

Step 1: low=0, high=9, mid=4 arr[4]=16 < 23 → search right half, low=5

Step 2: low=5, high=9, mid=7 arr[7]=56 > 23 → search left half, high=6

Step 3: low=5, high=6, mid=5 arr[5]=23 == 23 → found at index 5!

Three comparisons to find the target in a 10-element array. A linear scan would have needed six.

Pseudocode

function binarySearch(arr, target):
    low = 0
    high = length(arr) - 1

    while low <= high:
        mid = low + floor((high - low) / 2)

        if arr[mid] == target:
            return mid              // found it
        else if arr[mid] < target:
            low = mid + 1           // search right half
        else:
            high = mid - 1          // search left half

    return -1                       // not found

Why low <= high and not low < high?

The loop condition must be <= because low == high means there's still one unchecked element. Using < would skip checking the last remaining candidate and produce wrong results.

Common Off-by-One Pitfalls

Binary search is famously easy to get wrong. Jon Bentley reported that 90% of professional programmers failed to write a correct implementation given two hours. Here are the most common traps:

Bug #1: Using low < high instead of low <= high

// BUGGY: misses single-element ranges
Array: [5, 10, 15]
Target: 15

Step 1: low=0, high=2, mid=1 arr[1]=10 < 15 → low=2

Step 2: low=2, high=2 → loop condition "low < high" is FALSE We exit without ever checking arr[2]=15!

Result: -1 (wrong -- 15 is at index 2)

Bug #2: Setting high = mid instead of high = mid - 1

// BUGGY: can loop forever
Array: [3, 7]
Target: 3

Step 1: low=0, high=1, mid=0 arr[0]=3 == 3 → found! (works here)

But what if target=99?

Step 1: low=0, high=1, mid=0 arr[0]=3 < 99 → low=1

Step 2: low=1, high=1, mid=1 arr[1]=7 < 99 → low=2

Step 3: low=2, high=1 → low > high, exit correctly

Now imagine we wrote "high = mid" instead of "high = mid - 1": Step 1: low=0, high=1, mid=0, arr[0]=3 > target(1)? Say target=1: arr[0]=3 > 1 → high=mid=0

Step 2: low=0, high=0, mid=0 arr[0]=3 > 1 → high=mid=0 ← INFINITE LOOP!

Bug #3: Integer overflow in midpoint calculation

// BUGGY in languages with 32-bit integers
mid = (low + high) / 2

If low = 1,500,000,000 and high = 2,000,000,000: low + high = 3,500,000,000 → overflows 32-bit int!

// CORRECT mid = low + (high - low) / 2

high - low = 500,000,000 → safe mid = 1,750,000,000 → correct

Worked Example: Larger Array

Searching for 67 in a 16-element array

Array: [3, 7, 11, 15, 22, 29, 35, 41, 48, 53, 60, 67, 72, 81, 90, 99]
Index:  0  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
Target: 67

Step 1: low=0, high=15, mid=7 arr[7]=41 < 67 → low=8 [eliminated indices 0-7]

Step 2: low=8, high=15, mid=11 arr[11]=67 == 67 → found at index 11!

Only 2 comparisons for a 16-element array. log₂(16) = 4, so we're guaranteed at most 4 steps.

Notice that even in the worst case (element not found, or at the very edge), we'd make at most ⌈log2(n)⌉ + 1 comparisons. For a million elements, that's about 20 comparisons. For a billion, about 30.

Complexity Analysis

Time and Space

Time: O(log n) -- each step halves the search range. After k steps, the range has size n / 2k. We stop when this reaches 1, so k = log2(n).
Space: O(1) -- we only need three variables: low, high, and mid.

Binary Search vs. Linear Scan

Array sizeLinear scan (worst)Binary search (worst)
1010 comparisons4 comparisons
1,0001,00010
1,000,0001,000,00020
1,000,000,0001,000,000,00030

The difference is staggering. This is the power of logarithmic vs. linear growth.

Variations

The basic "find this exact value" version is just the starting point. Binary search has several important variations:

Lower Bound (first occurrence of target)

function lowerBound(arr, target):
    low = 0
    high = length(arr)        // note: NOT length-1

while low < high:         // note: strict <
    mid = low + floor((high - low) / 2)
    if arr[mid] < target:
        low = mid + 1
    else:
        high = mid        // note: NOT mid-1

return low                // index of first element >= target</code></pre>

Returns the index of the first element that is >= target. If the target appears multiple times, this finds the leftmost occurrence. If the target doesn't exist, it returns where it would be inserted to keep the array sorted.

Upper Bound (first element greater than target)

function upperBound(arr, target):
    low = 0
    high = length(arr)

while low < high:
    mid = low + floor((high - low) / 2)
    if arr[mid] <= target:    // note: <= instead of <
        low = mid + 1
    else:
        high = mid

return low                // index of first element > target</code></pre>

Returns the index of the first element strictly greater than the target. Together with lowerBound, you can count how many times a value appears: upperBound(arr, x) - lowerBound(arr, x).

Binary Search on the Answer

// Example: "What's the minimum capacity to ship all
// packages within D days?"

function canShipInDays(packages, capacity, days): // greedy check: can we ship with this capacity? ...

low = max(packages) // must fit largest package high = sum(packages) // ship everything in one day

while low < high: mid = low + floor((high - low) / 2) if canShipInDays(packages, mid, D): high = mid // try smaller capacity else: low = mid + 1 // need more capacity

return low

The "search space" isn't an array at all -- it's a range of possible answers. If the answer has a monotonic property (all values below some threshold fail, all above it pass), binary search finds the threshold.

Where Binary Search Is Used

ApplicationHow it uses binary search
Database indexes (B-trees) B-tree nodes use binary search to find the right child pointer among sorted keys
git bisect Binary search over commit history to find the exact commit that introduced a bug
Sorted containers Sorted arrays, sets, and maps use binary search for O(log n) lookups
Competitive programming "Binary search on the answer" solves optimization problems with monotonic predicates
System libraries C's bsearch(), Python's bisect, Java's Arrays.binarySearch()
Debugging Commenting out half the code at a time to isolate a bug is binary search in disguise

Key Takeaways

  • Binary search finds an element in a sorted array in O(log n) time by halving the search space each step
  • The loop invariant is that the target, if present, lies in arr[low..high]
  • Use low <= high, mid + 1, and mid - 1 for the standard version -- getting any of these wrong causes bugs
  • Compute the midpoint as low + (high - low) / 2 to avoid integer overflow
  • Variations like lower_bound and upper_bound use subtly different loop conditions and updates
  • "Binary search on the answer" generalizes the idea beyond arrays to any monotonic predicate
  • It's everywhere: databases, git bisect, standard libraries, and optimization problems

Try It Yourself -- Binary Search

Enter a sorted comma-separated list and a target value. Click Step to walk through the binary search one comparison at a time, or Run All to see every step at once.

Press Step or Run All to begin.

Binary search is deceptively simple -- the idea fits in one sentence, but getting the implementation exactly right takes care. Master the standard version, understand why each boundary condition matters, and you'll have a tool that applies far beyond sorted arrays.