Skip to the content.

24. Binary Search

Back to the index

Halve a sorted search range each step by comparing with the middle item. O(log n). The same idea finds the smallest value that satisfies any monotonic condition.

How it works

Keep a range [lo, hi] that must contain the target if it exists. Look at mid = (lo + hi) // 2. If a[mid] is too small, the target can only be right of mid; if too big, only left. Each step throws away half the range, so a million items need about 20 steps.

The pattern generalizes: binary search on the answer looks for the smallest x where check(x) becomes true (minimum capacity to ship packages in D days, Koko eating bananas, and so on).

Diagram

flowchart LR
    s0["lo 0 hi 8 mid 4, value 9"]
    s1["lo 5 hi 8 mid 6, value 13"]
    s2["lo 7 hi 8 mid 7, value 15"]
    s3["found at index 7"]
    s0 -->|"too small, go right"| s1
    s1 -->|"too small, go right"| s2
    s2 -->|"equal"| s3

Step-by-step trace

Input: Search for 15 in [1, 3, 5, 7, 9, 11, 13, 15, 17].

Step lo hi mid a[mid] Decision
1 0 8 4 9 9 < 15: lo = 5
2 5 8 6 13 13 < 15: lo = 7
3 7 8 7 15 equal: found at index 7

Result: Found at index 7.

Input: Search for 4 (not present).

Step lo hi mid a[mid] Decision
1 0 8 4 9 9 > 4: hi = 3
2 0 3 1 3 3 < 4: lo = 2
3 2 3 2 5 5 > 4: hi = 1
end 2 1 - - lo > hi: not found

Result: The range becomes empty, so the answer is -1. lo = 2 is where 4 would be inserted.

Complexity

Operation Time Space
Search in sorted array O(log n) O(1)
Search on answer over range V with an O(n) check O(n log V) O(1)

Python reference implementation

def binary_search(a, target):
    """Return the index of target in sorted list a, or -1."""
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == target:
            return mid
        if a[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

Common mistakes and tips


The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.

Previous: Heap Sort Next: Two Pointers