Skip to content

Binary Search

Search a sorted array by repeatedly halving the search interval.

Binary search finds a target value in a sorted sequence by repeatedly dividing the search space in half. At each step, it compares the target with the middle element and discards half of the remaining elements.

This reduces the problem size exponentially, which leads to logarithmic time complexity.

Problem

Given a sorted array AA of length nn and a value xx, find an index ii such that

A[i]=x A[i] = x

If no such index exists, return 1-1.

Key Idea

Maintain a search interval [l,r][l, r]. At each step:

  • Compute midpoint mm
  • Compare A[m]A[m] with xx
  • Eliminate half of the interval

Algorithm

binary_search(A, x):
    l = 0
    r = length(A) - 1

    while l <= r:
        m = l + (r - l) // 2

        if A[m] == x:
            return m
        else if A[m] < x:
            l = m + 1
        else:
            r = m - 1

    return -1

Example

Let

A=[1,3,5,7,9,11] A = [1, 3, 5, 7, 9, 11]

and

x=7 x = 7

Steps:

steplrmA[m]action
10525move right
23549move left
33337found

Return index 33.

Correctness

At each step, the algorithm maintains the invariant:

  • If xx exists in AA, then it must lie within [l,r][l, r]

Each comparison removes half of the remaining candidates while preserving this invariant. When l>rl > r, the interval is empty, so xx does not exist.

Complexity

casecomparisonstime
best11O(1)O(1)
worstlog2n+1\lfloor \log_2 n \rfloor + 1O(logn)O(\log n)
averageO(logn)O(\log n)O(logn)O(\log n)

Space complexity:

  • Iterative: O(1)O(1)
  • Recursive: O(logn)O(\log n) due to call stack

Requirements

Binary search requires:

  • The array must be sorted
  • Random access to elements

If either condition fails, correctness or efficiency breaks.

Common Variants

Binary search generalizes to:

  • Lower bound (first x\ge x)
  • Upper bound (first >x> x)
  • First true in monotone predicate
  • Search on answer space

These variants rely on the same invariant: monotonicity.

Implementation

def binary_search(a, x):
    l, r = 0, len(a) - 1
    while l <= r:
        m = l + (r - l) // 2
        if a[m] == x:
            return m
        elif a[m] < x:
            l = m + 1
        else:
            r = m - 1
    return -1
func BinarySearch(a []int, x int) int {
    l, r := 0, len(a)-1
    for l <= r {
        m := l + (r-l)/2
        if a[m] == x {
            return m
        } else if a[m] < x {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return -1
}