Lesson 7 · Core algorithms

Binary Search

Binary search finds a value in a sorted array by checking the middle of the range that could still hold it and throwing away the half that cannot. Each probe halves the range, so it needs about log2 n probes.

Binary Search concept diagramA visual explanation of the layout and operations shown in this lesson.each comparison discards half of the remaining interval205182123164215296middiscarded: 12 < 16still possible
1

How Binary Search Works

  1. Set lo = 0 and hi = n - 1: the whole array may hold the target
  2. While lo <= hi, compute mid = lo + (hi - lo) / 2
  3. If a[mid] equals the target, return mid
  4. If a[mid] is smaller, the target can only be to the right: lo = mid + 1
  5. Otherwise it can only be to the left: hi = mid - 1
  6. If the loop ends with lo > hi, the target is absent: return -1

Binary search finds a target in a sorted array. It keeps a range [lo, hi] that must contain the target if the target is present at all, looks at the middle value, and throws away the half that cannot hold it. The steps above are exactly what the code below does.

Why is throwing half away safe? Because the array is sorted. If a[mid] is 12 and the target is 16, every value at or left of mid is at most 12, so none of them can be 16. One comparison removes half the candidates.

That halving is where the speed comes from. After k probes at most n / 2^k candidates remain, so the search ends after about log2 n probes: 20 for a million values, 30 for a billion. A linear scan of the same billion values could take a billion comparisons.

It is also famously easy to get wrong. Jon Bentley reported that about 90% of the professional programmers he tested left bugs in their version, and Java's Arrays.binarySearch carried an overflow bug for about nine years before it was found in 2006. The bugs almost always come from a range convention that the loop test and the updates do not agree on.

  • Precondition: sorted data with O(1) access by index (an array, not a linked list)
  • The range only ever shrinks, and the target never leaves it
  • On a miss, lo ends where the target would be inserted
2

Closed or Half-Open Ranges

There are two common ways to write the range, and each line of the loop follows from the one you choose.

With a closed range [lo, hi], both ends are real indexes. hi starts at n - 1, the loop runs while lo <= hi, and both updates skip mid (lo = mid + 1, hi = mid - 1), because mid has been checked. This is the natural form for finding one exact value.

With a half-open range [lo, hi), hi is one past the last candidate. It starts at n, the loop runs while lo < hi, and the range is empty exactly when lo == hi. Moving left is hi = mid, not mid - 1, because hi is already excluded. This form suits the boundary searches below.

Mixing the two is the classic bug. A closed loop test with a half-open update skips a value or loops forever. Every iteration must also make the range strictly smaller. With two values left, mid rounds down to lo, so writing lo = mid leaves the range unchanged and the loop never ends.

The midpoint. mid = (lo + hi) / 2 can overflow when lo + hi is larger than the biggest int, giving a negative index. That was the Java bug. mid = lo + (hi - lo) / 2 computes the same value without the large sum. Python integers never overflow, but the habit carries over to every other language.

The two range conventions side by side
Closed [lo, hi]Half-open [lo, hi)
Startlo = 0, hi = n - 1lo = 0, hi = n
Loop testlo <= hilo < hi
Empty whenlo > hilo == hi
Move lefthi = mid - 1hi = mid
Move rightlo = mid + 1lo = mid + 1
  • Choose the convention first; the loop test and updates follow from it
  • Each iteration must shrink the range, or the loop never ends
  • Use lo + (hi - lo) / 2 in C, C++ and Java
3

Lower Bound and Upper Bound

With duplicates, an exact search returns some matching index, not a particular one. In [1, 3, 3, 3, 5, 8] it could return any of the three 3s. Two boundary searches give precise answers.

Lower bound is the first index whose value is not less than the target. If the target is present, it is the first copy; if not, it is where the target would be inserted. Upper bound is the first index whose value is strictly greater than the target. For 3 in the array above, lower bound is 1 and upper bound is 4.

Together they give the count of a value, upper - lower, in O(log n) without scanning the run of duplicates. The value is present exactly when that count is above zero.

Both use a half-open range and never stop early. Finding a 3 does not end a lower-bound search, because an earlier 3 may exist. The test is two-way: for lower bound, a[mid] < target sends lo to mid + 1 and anything else sets hi = mid. Upper bound changes only the test, to a[mid] <= target.

Libraries provide both: lower_bound and upper_bound in C++, bisect_left and bisect_right in Python. Java's Arrays.binarySearch returns any match, or -(insertion point) - 1 when the value is missing. Problems such as Search Insert Position and Find First and Last Position of Element in Sorted Array are these two searches.

Three searches on [1, 3, 3, 3, 5, 8] with target 3
SearchReturnsTest at midAnswer
ExactAny index of the target, or -1Three-way, stops on a match1, 2 or 3
Lower boundFirst index with value ≥ targeta[mid] < target1
Upper boundFirst index with value > targeta[mid] <= target4
  • Count of a value = upper bound - lower bound
  • Neither boundary search stops on a match
  • On a missing value both return the insertion point
Key reference

Terms, operations, and practical uses

Interval vocabulary

  • InvariantThe statement about lo and hi that every iteration must preserve.
  • Half-open interval[lo, hi) — empty exactly when lo equals hi, with size hi minus lo.
  • Monotonic predicateA yes/no condition that flips at most once across the ordered domain.

Boundary variants

  • Lower boundThe first position whose value is greater than or equal to the target.
  • Upper boundThe first position whose value is strictly greater than the target.
  • Occurrence countUpper bound minus lower bound, computed without scanning the duplicates.

Common failure modes

  • Overflow(lo + hi) / 2 can overflow fixed-width integers; use lo + (hi - lo) / 2.
  • Infinite loopAn update that does not shrink the interval, such as lo = mid when mid equals lo.
  • Unsorted inputBinary search silently returns a wrong answer rather than failing loudly.

Cost

  • TimeO(log n): each comparison halves the remaining range; O(1) when the first probe hits.
  • SpaceO(1) iteratively; O(log N) call stack if written recursively.
  • PreconditionSorted, randomly accessible data, or a provably monotonic predicate.
Implementation

Code in Python, C++ and Java

def binary_search(values, target):
    lo, hi = 0, len(values) - 1
    while lo <= hi:
        mid = lo + (hi - lo) // 2   # avoids overflow in fixed-width ints
        if values[mid] == target:
            return mid
        if values[mid] < target:
            lo = mid + 1            # the target must lie to the right
        else:
            hi = mid - 1            # the target must lie to the left
    return -1


print('index', binary_search([2, 5, 8, 12, 16, 21, 29], 16))
#include <iostream>
#include <vector>
using namespace std;

int binary_search(vector<int>& values, int target) {
    int lo = 0, hi = values.size() - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;   // avoids overflow in fixed-width ints
        if (values[mid] == target) return mid;
        if (values[mid] < target) lo = mid + 1;   // the target must lie to the right
        else hi = mid - 1;                       // the target must lie to the left
    }
    return -1;
}

int main() {
    vector<int> values = {2, 5, 8, 12, 16, 21, 29};
    cout << "index " << binary_search(values, 16) << '\n';
}
public class Main {
    static int binarySearch(int[] values, int target) {
        int lo = 0, hi = values.length - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;   // avoids overflow in fixed-width ints
            if (values[mid] == target) return mid;
            if (values[mid] < target) lo = mid + 1;   // the target must lie to the right
            else hi = mid - 1;                        // the target must lie to the left
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] values = {2, 5, 8, 12, 16, 21, 29};
        System.out.println("index " + binarySearch(values, 16));
    }
}
Watch it run

Step through it

Running on [2, 5, 8, 12, 16, 21, 29], target 16; then [1, 3, 3, 3, 5, 8], target 3

exact search for 16, closed range [lo, hi]205182123164215296lohilohilo = 0, hi = 6: all 7 values are still candidatesthe loop runs while lo <= hi
Step 1

A sorted array and the whole range

The code keeps a closed range [lo, hi]: both ends are real indexes, so hi starts at n - 1 = 6 and the loop runs while lo <= hi. The promise it keeps is simple: if 16 is in the array, it sits somewhere between lo and hi. Sorting is what makes that promise checkable from one value.

Output
1 / 14
4

Recursive Binary Search, Cost and Edge Cases

A recursive binary search passes the range as arguments: check mid, then call itself on the left or right half, with lo > hi as the base case that returns -1. Each call does the same work as one loop iteration, so the time is the same, O(log n). The recursion depth is also O(log n), about 30 frames for a billion values, so the stack is never at risk, but the loop version uses O(1) extra space and is what libraries ship.

Time is O(log n) in the worst and average case and O(1) in the best case, when the first mid is the target. Space is O(1) for the loop and O(log n) for the recursion.

The edge cases worth testing: an empty array (the loop never runs, return -1), a single element, a target smaller than everything (lo stays 0) or larger than everything (lo ends at n), and a run of duplicates. On a linked list the idea fails, because reaching the middle costs O(n) steps.

  • Recursive and iterative versions do the same probes
  • Best case O(1), worst case O(log n)
  • Test empty, single-element, out-of-range and duplicate inputs
5

Searching an Answer Space

The same halving works without any array. What it really needs is a yes/no question over an ordered range whose answer switches from no to yes exactly once, such as "can every package ship within D days at capacity C?" If capacity C works, every larger capacity works too.

Then binary search runs over the possible answers: try a middle capacity, check it in O(n), and keep the half where the switch must be. The total cost is O(n log R), where R is the size of the answer range. Even a range of a billion values needs only about 30 checks.

The signal is a problem asking to minimise a maximum or maximise a minimum: Koko Eating Bananas, Capacity to Ship Packages Within D Days and Aggressive Cows all follow it. If the check is not monotone, the method does not apply.

On a range of real numbers, lo == hi may never happen. Run a fixed number of halvings instead; 100 iterations shrink the range far below any useful precision. For how binary search compares with linear and other searches, see searching algorithms.

  • Needs a yes/no test that flips once over an ordered range
  • Cost: O(log R) checks, each usually O(n)
  • For real numbers, loop a fixed number of times
  • Full walkthrough: binary search on answer; first and last occurrence, rotated arrays and peaks: binary search variations