algossearching

binary search

halve a sorted range until the target is found or the range is empty.

report a mistake
.md

look at the middle of a sorted range and drop the half that can't hold the answer.

time
O(log n) 20 looks for a million items
space
O(1) two indexes
needs
sorted input or a yes or no question that flips once
duplicates
first copy the lower bound finds the leftmost
reach for it
  • lookups in a sorted array
  • where a new item goes
  • the first and last copy
  • the smallest answer that works
on this page
  1. the idea
  2. watch it run
  3. try it
  4. pseudocode
  5. the key step up close
  6. complexity
  7. implementations
  8. pitfalls
  9. variants
  10. practice
  11. sources

the idea

a sorted array answers questions fast. look at the middle item. if it’s smaller than what you want, so is everything left of it, and half the array is gone after one look. keep halving, and a million items take 20 looks. here’s a search for 44:

twelve sorted numbers, and we want 44. lo and hi mark the range still in play: from 0 up to 12, so all of it.

an animation: twelve sorted numbers, 3 to 63, searched for 44. the first look, at index 6, finds 27: too small, so indexes 0 to 6 drop out and lo moves to 7. the second look, at 9, finds 44: big enough, so hi stops at 9 and indexes 10 and 11 drop out. the third look, at 8, finds 36: too small, so lo moves to 9 and meets hi. index 9 holds 44: found after 3 looks, where a scan from the left takes 10.

watch it run

pick a size, then tap a number to search for it, or ask for one that isn’t there. lo is cyan, hi is amber, and the item being looked at is white. cells tinted cyan are known to be too small, and cells tinted amber are known to be big enough. the pseudocode follows along.

sorted numbers

tap a number to search for it, or the slot after the last.

the answer is somewhere in 0 .. 12: all 12 items are in play

x
30
looks
0
step
1 of 15
pseudocode
lower_bound(a, x):  lo, hi = 0, len(a)  # the answer is somewhere in lo .. hi  while lo < hi:    mid = lo + (hi - lo) // 2    if a[mid] < x:      lo = mid + 1  # a[mid] and everything left of it is too small    else:      hi = mid  # a[mid] is big enough, so it may be the answer  return lo contains(a, x):  i = lower_bound(a, x)  return i < len(a) and a[i] == x

an interactive stepper: 8, 12 or 16 sorted numbers in a row, with lo, mid and hi marked under them and a bracket over the range still in play. tap a number to search for it, tap the slot after the last for a number bigger than all of them, or ask for a number that isn't there. each step shows the comparison and which end moves, with the matching pseudocode line and a count of looks.

try it

searching for 30, with lo = 0 and hi = 12: a[6] is 27. what happens next?

pick one.

0 / 0 right

a practice exercise with four kinds of question: which index mid lands on for a given lo and hi, what happens to lo or hi after a comparison, at most how many looks a search through n items takes, and where a missing number would go, answered by tapping its slot.

pseudocode

pseudocode
lower_bound(a, x):
  lo, hi = 0, len(a)  # the answer is somewhere in lo .. hi
  while lo < hi:
    mid = lo + (hi - lo) // 2
    if a[mid] < x:
      lo = mid + 1  # a[mid] and everything left of it is too small
    else:
      hi = mid  # a[mid] is big enough, so it may be the answer
  return lo

contains(a, x):
  i = lower_bound(a, x)
  return i < len(a) and a[i] == x

the range is half-open: lo is in play and hi isn’t. it starts as 0 up to len(a), so hi can sit one past the end, which is where a number bigger than everything would go. contains is lower_bound plus one comparison.

the key step up close

three zones

  • left of lo: smaller than 44. out, and nothing here can be the answer
  • lo up to hi: not looked at yet. the answer is in here, or it's hi
  • hi and on: at least 44. the first of them, at hi, is the best answer so far

the twelve numbers partway through the search for 44, with lo at 7 and hi at 9. indexes 0 to 6 are tinted cyan: smaller than 44. indexes 7 and 8 are plain: not looked at yet. indexes 9 to 11 are tinted amber: at least 44, and index 9 is the best answer so far.

each look moves one wall and keeps both statements true. when lo meets hi, nothing is left in between, so lo is the first index whose item is at least x: where x is, or where it would go. go’s slices.BinarySearch states the same two facts in a comment above its loop.1

mid + 1, but hi = mid

the overflow

mid = (lo + hi) / 2 reads fine, but with 32-bit ints lo + hi can pass 2,147,483,647 and wrap around to a negative number. 1,500,000,000 + 2,000,000,000 comes out as -794,967,296, and half of that is a negative index.

complexity

0102030110241.05mscan
binary search
21 looks
scan
1,048,576 looks

a chart of looks against items, from 1 to 1,048,576 on a doubling scale. binary search climbs by one look each time the items double, to 21 at 1,048,576. a scan from the left climbs with the items and leaves the top of the chart before 32.

implementations

each tab is the real file from the repo, checked by its tests (python -m unittest, make test, go test, cargo test, swift test, vitest). each one checks 2000 seeded searches against a scan from the left.

go/algos/binarysearch/binarysearch.go
// Package binarysearch is a reference binary search on a sorted slice of ints. each step looks at the
// middle of the range still in play and drops the half that can't hold the answer, so n items take about
// log2 n steps. the searches keep a half-open range [lo, hi) and never stop early: they always halve down
// to one spot.
package binarysearch

// midpoint returns the middle of [lo, hi), rounded down. lo + (hi - lo) / 2 stays in range where
// (lo + hi) / 2 may not: an int has a fixed size, so lo + hi can run past math.MaxInt and wrap.
func midpoint(lo, hi int) int {
	return lo + (hi-lo)/2
}

// LowerBound returns the first index whose item is at least x, or len(a) if every item is smaller:
// where x is, or where it would go. a must be sorted.
func LowerBound(a []int, x int) int {
	lo, hi := 0, len(a)
	for lo < hi {
		mid := midpoint(lo, hi)
		if a[mid] < x {
			lo = mid + 1 // a[mid] and everything left of it is too small
		} else {
			hi = mid // a[mid] is big enough, so it may be the answer: keep it
		}
	}
	return lo
}

// UpperBound returns the first index whose item is bigger than x, or len(a). The copies of x sit
// between the two bounds.
func UpperBound(a []int, x int) int {
	lo, hi := 0, len(a)
	for lo < hi {
		mid := midpoint(lo, hi)
		if a[mid] <= x {
			lo = mid + 1
		} else {
			hi = mid
		}
	}
	return lo
}

// Contains reports whether x is in a: its lower bound, then one comparison.
func Contains(a []int, x int) bool {
	i := LowerBound(a, x)
	return i < len(a) && a[i] == x
}
rust/algos/src/binary_search.rs
//! binary search on a sorted slice of ints. each step looks at the middle of the range still in play and drops the half that can't hold the answer, so n items take about log2 n steps. the searches here keep a half-open range [lo, hi) and never stop early: they always halve down to one spot.
//!
//! the standard library has these on slices: `partition_point` gives either bound, and `binary_search` finds an item or the spot it would go. this file spells the loop out to show it.

/// The middle of [lo, hi), rounded down. `lo + (hi - lo) / 2` stays in range where
/// `(lo + hi) / 2` may not: `lo + hi` can run past `usize::MAX`, and that panics in a debug
/// build and wraps in a release one.
pub fn midpoint(lo: usize, hi: usize) -> usize {
    lo + (hi - lo) / 2
}

/// The first index whose item is at least `x`, or `a.len()` if every item is smaller: where `x`
/// is, or where it would go. `a` must be sorted.
pub fn lower_bound(a: &[i32], x: i32) -> usize {
    let mut lo = 0;
    let mut hi = a.len();
    while lo < hi {
        let mid = midpoint(lo, hi);
        if a[mid] < x {
            lo = mid + 1; // a[mid] and everything left of it is too small
        } else {
            hi = mid; // a[mid] is big enough, so it may be the answer: keep it
        }
    }
    lo
}

/// The first index whose item is bigger than `x`, or `a.len()`. The copies of `x` sit between
/// the two bounds.
pub fn upper_bound(a: &[i32], x: i32) -> usize {
    let mut lo = 0;
    let mut hi = a.len();
    while lo < hi {
        let mid = midpoint(lo, hi);
        if a[mid] <= x {
            lo = mid + 1;
        } else {
            hi = mid;
        }
    }
    lo
}

/// Whether `x` is in `a`: its lower bound, then one comparison.
pub fn contains(a: &[i32], x: i32) -> bool {
    let i = lower_bound(a, x);
    i < a.len() && a[i] == x
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The first index whose item passes `ok`, or `a.len()` if none does. A linear scan, to
    /// check the searches against.
    fn first(a: &[i32], ok: impl Fn(i32) -> bool) -> usize {
        a.iter().position(|&v| ok(v)).unwrap_or(a.len())
    }

    // the page's 12 numbers
    const PAGE: [i32; 12] = [3, 8, 11, 15, 19, 23, 27, 31, 36, 44, 52, 63];

    #[test]
    fn an_empty_array_both_bounds_are_0_and_nothing_is_in_it() {
        assert_eq!(
            (lower_bound(&[], 5), upper_bound(&[], 5), contains(&[], 5)),
            (0, 0, false)
        );
    }

    #[test]
    fn one_item_below_it_on_it_and_above_it() {
        let a = [5];
        assert_eq!(
            (lower_bound(&a, 4), upper_bound(&a, 4), contains(&a, 4)),
            (0, 0, false)
        );
        assert_eq!(
            (lower_bound(&a, 5), upper_bound(&a, 5), contains(&a, 5)),
            (0, 1, true)
        );
        assert_eq!(
            (lower_bound(&a, 6), upper_bound(&a, 6), contains(&a, 6)),
            (1, 1, false)
        );
    }

    #[test]
    fn the_pages_12_numbers_44_is_found_at_9_and_30_would_go_at_7() {
        assert_eq!((lower_bound(&PAGE, 44), contains(&PAGE, 44)), (9, true));
        assert_eq!((lower_bound(&PAGE, 30), contains(&PAGE, 30)), (7, false));
        assert_eq!(
            (
                lower_bound(&PAGE, 2),
                lower_bound(&PAGE, 100),
                upper_bound(&PAGE, 63)
            ),
            (0, 12, 12)
        );
    }

    #[test]
    fn duplicates_the_lower_bound_is_the_first_copy_the_upper_bound_the_spot_after_the_last() {
        let a = [1, 2, 2, 2, 3];
        assert_eq!(
            (lower_bound(&a, 2), upper_bound(&a, 2), contains(&a, 2)),
            (1, 4, true)
        );
        assert_eq!(
            (lower_bound(&a, 0), upper_bound(&a, 3), lower_bound(&a, 4)),
            (0, 5, 5)
        );
    }

    #[test]
    fn the_midpoint_stays_in_range_where_lo_plus_hi_would_wrap() {
        let (lo, hi) = (usize::MAX - 2, usize::MAX);
        // the sum runs past usize::MAX: checked_add says so, and wrapping_add comes back around
        // to usize::MAX - 3, so half of it lands far below lo
        let sum = lo.wrapping_add(hi);
        assert_eq!(
            (lo.checked_add(hi), sum, sum / 2),
            (None, usize::MAX - 3, usize::MAX / 2 - 1)
        );
        assert_eq!(midpoint(lo, hi), usize::MAX - 1);
        assert_eq!((midpoint(0, 1), midpoint(3, 4), midpoint(7, 12)), (0, 3, 9));
    }

    #[test]
    fn agrees_with_a_linear_scan_on_2000_seeded_queries() {
        // xorshift32 seeded with 42, like the other tests here
        let mut state: u32 = 42;
        let mut next = || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state as usize
        };
        // small values, so most arrays have duplicates, and x lands on, between and outside them
        for _ in 0..2000 {
            let mut a: Vec<i32> = (0..next() % 31).map(|_| (next() % 20) as i32).collect();
            a.sort();
            let x = (next() % 22) as i32 - 1;
            assert_eq!(lower_bound(&a, x), first(&a, |v| v >= x));
            assert_eq!(upper_bound(&a, x), first(&a, |v| v > x));
            // a.contains is the slice's own method: a linear scan
            assert_eq!(contains(&a, x), a.contains(&x));
        }
    }
}
site/src/visuals/binary-search/binary-search.ts
/**
 * Binary search on a sorted array of numbers. Each step looks at the middle of the range still in play and drops
 * the half that can't hold the answer, so n items take about log2 n steps. The searches here keep a half-open
 * range [lo, hi) and never stop early: they always halve down to one spot.
 */

/** The middle of [lo, hi), rounded down. lo + (hi - lo) / 2 stays in range where (lo + hi) / 2 may not: in a
 * fixed-size int, lo + hi can run past the biggest value and wrap. */
export function midpoint(lo: number, hi: number): number {
  return lo + Math.floor((hi - lo) / 2);
}

/** The first index whose item is at least x, or a.length if every item is smaller: where x is, or where it would
 * go. a must be sorted. */
export function lowerBound(a: readonly number[], x: number): number {
  let lo = 0;
  let hi = a.length;
  while (lo < hi) {
    const mid = midpoint(lo, hi);
    if (a[mid] < x)
      lo = mid + 1; // a[mid] and everything left of it is too small
    else hi = mid; // a[mid] is big enough, so it may be the answer: keep it
  }
  return lo;
}

/** The first index whose item is bigger than x, or a.length. The copies of x sit between the two bounds. */
export function upperBound(a: readonly number[], x: number): number {
  let lo = 0;
  let hi = a.length;
  while (lo < hi) {
    const mid = midpoint(lo, hi);
    if (a[mid] <= x) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

/** Whether x is in a: its lower bound, then one comparison. */
export function contains(a: readonly number[], x: number): boolean {
  const i = lowerBound(a, x);
  return i < a.length && a[i] === x;
}
c/algos/binary_search.c
/* binary search on a sorted array of ints. each step looks at the middle of the range still in play and drops the half that can't hold the answer, so n items take about log2 n steps. the searches here keep a half-open range [lo, hi) and never stop early: they always halve down to one spot. */
#include "binary_search.h"

/* lo + (hi - lo) / 2 stays in range where (lo + hi) / 2 may not: a size_t tops out at SIZE_MAX, and
   lo + hi can run past it and wrap around to a number below lo */
size_t bs_midpoint(size_t lo, size_t hi) {
    return lo + (hi - lo) / 2;
}

/* every item left of lo is smaller than x, and every item from hi on is at least x. each step moves
   lo up or hi down, until the range is empty and lo is on the first item that's at least x, or at
   n. with n = 0 the loop doesn't run, so a can be NULL */
size_t bs_lower_bound(const int *a, size_t n, int x) {
    size_t lo = 0, hi = n;
    while (lo < hi) {
        size_t mid = bs_midpoint(lo, hi);
        if (a[mid] < x) lo = mid + 1; /* a[mid] and everything left of it is too small */
        else hi = mid; /* a[mid] is big enough, so it may be the answer: keep it */
    }
    return lo;
}

/* the lower bound's search with <= in place of <: a copy of x counts as too small, so lo ends up
   just past the last copy */
size_t bs_upper_bound(const int *a, size_t n, int x) {
    size_t lo = 0, hi = n;
    while (lo < hi) {
        size_t mid = bs_midpoint(lo, hi);
        if (a[mid] <= x) lo = mid + 1;
        else hi = mid;
    }
    return lo;
}

/* i is n when every item is smaller than x, and a[n] is past the end, so i < n goes first */
bool bs_contains(const int *a, size_t n, int x) {
    size_t i = bs_lower_bound(a, n, x);
    return i < n && a[i] == x;
}
swift/algos/BinarySearch.swift
/// binary search on a sorted array of ints. each step looks at the middle of the range still in play and drops the half that can't hold the answer, so n items take about log2 n steps. the searches here keep a half-open range [lo, hi) and never stop early: they always halve down to one spot.

/// the middle of [lo, hi), rounded down. lo + (hi - lo) / 2 stays in range where (lo + hi) / 2 may not: lo + hi
/// can run past Int.max, and swift's + traps when it does
public func midpoint(_ lo: Int, _ hi: Int) -> Int {
    lo + (hi - lo) / 2
}

/// the first index whose item is at least x, or a.count if every item is smaller: where x is, or where it would
/// go. a must be sorted
public func lowerBound(_ a: [Int], _ x: Int) -> Int {
    var lo = 0
    var hi = a.count
    while lo < hi {
        let mid = midpoint(lo, hi)
        if a[mid] < x {
            lo = mid + 1 // a[mid] and everything left of it is too small
        } else {
            hi = mid // a[mid] is big enough, so it may be the answer: keep it
        }
    }
    return lo
}

/// the first index whose item is bigger than x, or a.count. the copies of x sit between the two bounds
public func upperBound(_ a: [Int], _ x: Int) -> Int {
    var lo = 0
    var hi = a.count
    while lo < hi {
        let mid = midpoint(lo, hi)
        if a[mid] <= x { lo = mid + 1 } else { hi = mid }
    }
    return lo
}

/// whether x is in a: its lower bound, then one comparison
public func contains(_ a: [Int], _ x: Int) -> Bool {
    let i = lowerBound(a, x)
    return i < a.count && a[i] == x
}
python/algos/binary_search.py
"""binary search on a sorted list of ints. each step looks at the middle of the range still in play and drops the half that can't hold the answer, so n items take about log2 n steps. the searches here keep a half-open range [lo, hi) and never stop early: they always halve down to one spot."""

from __future__ import annotations


def midpoint(lo: int, hi: int) -> int:
    """Return the middle of [lo, hi), rounded down.

    lo + (hi - lo) // 2 stays in range where (lo + hi) // 2 may not: in a fixed-size int, lo + hi can run
    past the biggest value and wrap. Python's ints grow instead, so here the two agree.
    """
    return lo + (hi - lo) // 2


def lower_bound(a: list[int], x: int) -> int:
    """Return the first index whose item is at least x, or len(a) if every item is smaller.

    That's where x is, or where it would go. a must be sorted.
    """
    lo, hi = 0, len(a)
    while lo < hi:
        mid = midpoint(lo, hi)
        if a[mid] < x:
            lo = mid + 1  # a[mid] and everything left of it is too small
        else:
            hi = mid  # a[mid] is big enough, so it may be the answer: keep it
    return lo


def upper_bound(a: list[int], x: int) -> int:
    """Return the first index whose item is bigger than x, or len(a).

    The copies of x sit between the two bounds.
    """
    lo, hi = 0, len(a)
    while lo < hi:
        mid = midpoint(lo, hi)
        if a[mid] <= x:
            lo = mid + 1
        else:
            hi = mid
    return lo


def contains(a: list[int], x: int) -> bool:
    """Return True if x is in a: its lower bound, then one comparison."""
    i = lower_bound(a, x)
    return i < len(a) and a[i] == x

the standard libraries have these already:

pitfalls

variants

practice

sources

  1. slices.BinarySearch (opens in a new tab) at go1.27.3: its comments name the two invariants, every item left of i is smaller than the target and every item from j on is at least the target, and its last line checks for NaN. ↩ ↩2 ↩3

  2. joshua bloch, nearly all binary searches and mergesorts are broken (opens in a new tab), google research, 2006. ↩

  3. JDK-5045582 (opens in a new tab) in the jdk bug tracker: binarySearch failing for arrays bigger than 2^30, reported in 2004 and fixed in java 6. ↩

  4. Arrays.java (opens in a new tab) at jdk-27-ga: binarySearch0 for ints, with (low + high) >>> 1 and -(low + 1) for a missing key. ↩ ↩2

  5. sort.Search (opens in a new tab) at go1.27.3, which computes its midpoint as int(uint(i+j) >> 1), commented as a way to avoid overflow. ↩ ↩2

  6. bisect.py (opens in a new tab) in cpython 3.15.0, whose bisect_left is the lower bound with mid = (lo + hi) // 2. a c version (opens in a new tab) replaces it when it’s available, and casts to size_t before adding so the sum can’t overflow. ↩ ↩2 ↩3

  7. slice::binary_search (opens in a new tab) at rust 1.99.1, whose docs say any one of several matches can come back. the loop it runs (opens in a new tab) skips an early exit on purpose, so the number of passes depends only on the length. partition_point (opens in a new tab) takes the question as a function: its examples use x < 5 for the lower bound and x <= num for the spot after the last copy. ↩

  8. stdlib-bsearch.h (opens in a new tab) in glibc 2.42: bsearch halves a count instead of keeping two indexes, and returns as soon as the comparison says equal. ↩

  9. partitioningIndex(where:) (opens in a new tab) in swift-algorithms 1.2.1. ↩

  10. git bisect (opens in a new tab) in the git docs. ↩