algossearching
binary search
halve a sorted range until the target is found or the range is empty.
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
- lookups in a sorted array
- where a new item goes
- the first and last copy
- the smallest answer that works
on this page
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:
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.
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
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] == xan 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.
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
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] == xthe 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.
- everything left of
lois smaller thanx - everything from
hion is at leastx - in between,
loup tohi, nothing is known yet
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
a[mid] < x: mid itself is too small, so lo skips past it,lo = mid + 1- otherwise
a[mid]is big enough and might be the answer, so hi stops on it,hi = mid.hi = mid - 1would throw the answer away lo = midinstead ofmid + 1can loop forever. withlo = 3andhi = 4, mid is 3, and ifa[3]is too small, lo stays at 3- mid rounds down, so it’s always below hi, and every look shrinks the range by at least one
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.
- java’s
Arrays.binarySearchhad this bug for about nine years before it broke someone’s program. so did the binary search that bentley proves correct in programming pearls. it bites once an array holds 2^30 items or more.2,3 lo + (hi - lo) / 2never goes past hi, so it can’t wrap. every file on this page uses it- java now adds the two and shifts with
>>> 1, which reads the wrapped sum as unsigned.4 go converts the sum to an unsigned int before its shift, with a comment saying why.5 cpython’s c version casts tosize_t6 - python’s own ints never wrap, so the plain
(lo + hi) // 2inbisect.pyis safe there6
complexity
- 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.
- each look halves the range, rounding down, so n items take at most floor(log₂ n) + 1 looks: the number of bits in n
- these searches never stop early, so every search takes floor(log₂ n) looks or one more, whatever
xis - 1,000,000 items: 20 looks at most. 1,048,576 = 2^20 items: 21. a scan from the left may look at all of them
- space: two indexes, O(1). a recursive version keeps O(log n) frames on the stack
- the catch is the sort. sorting costs O(n log n), so for one lookup a scan is cheaper. binary search pays off when the same array answers many questions
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.
// 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
}//! 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));
}
}
}/**
* 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;
}/* 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;
}/// 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
}"""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] == xthe standard libraries have these already:
- python.
bisect.bisect_leftandbisect_rightare the lower and upper bound6 - go.
slices.BinarySearchreturns the lower bound and whetherxis there.1sort.Search(n, f)takes the yes or no question as a function5 - rust.
partition_pointgives either bound.binary_searchreturnsOkwith the index of a match, orErrwith wherexwould go. with duplicates, it can return any of them, and it never stops early, so the loop runs the same number of times for everyx7 - java.
Arrays.binarySearchreturns the index, or-(where it would go) - 1whenxisn’t there4 - c.
bsearchreturns a pointer to a match, orNULL. it can’t tell you where a missing item would go8 - swift. the standard library has none. swift-algorithms adds
partitioningIndex(where:), the lower bound for any yes or no question9
pitfalls
- the array must be sorted, by the same order you search with. nothing checks. an unsorted array gives wrong answers, not an error
- mixing styles: a half-open range with
while lo <= hi, orhi = len(a) - 1withhi = mid. pick one and keep its rules lo = midwhena[mid]is too small: it loops forever once two items are left(lo + hi) / 2with fixed-size ints- stopping at the first match you see. with duplicates it can be any copy. search for the bound you want
- floats: NaN isn’t smaller, bigger or equal to anything, so it breaks the order. go’s
slices.BinarySearchchecks for it by hand1
variants
- lower and upper bound.
upper_boundswaps<for<=and lands just past the last copy. the copies ofxsit from the lower bound up to the upper, so the difference counts them - search on the answer. binary search works on any yes or no question whose answer flips once, from no to yes. “can koko eat every banana in h hours, at k bananas an hour?” is no for small k and yes from some k on, so search k from 1 up to the biggest pile. go’s
sort.Search, rust’spartition_pointand swift-algorithms’partitioningIndexall take the question as a function - git bisect. binary search over history: mark a good commit and a bad one, and git checks out commits in between until it finds the one that broke things10
- rotated arrays. a sorted array turned around some point, like
[5, 6, 1, 2, 3, 4]. one half of any range is still sorted, so check which, then whetherxfalls inside it - exponential search. for a list whose length you don’t know: check index 1, 2, 4, 8 and so on until you pass
x, then binary search the last stretch. O(log i) forxat index i - binary insertion sort. insertion sort with a binary search for each item’s spot: fewer comparisons, the same shifts
- as a tree. a binary search tree keeps the halving in its shape, so inserts stay cheap too
practice
- binary search (opens in a new tab):
contains, on a sorted array - search insert position (opens in a new tab): the lower bound
- find first and last position of element in sorted array (opens in a new tab): the lower and the upper bound
- first bad version (opens in a new tab): git bisect in miniature
- koko eating bananas (opens in a new tab): search on the answer
- search in rotated sorted array (opens in a new tab): find the sorted half first
sources
-
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
-
joshua bloch, nearly all binary searches and mergesorts are broken (opens in a new tab), google research, 2006. ↩
-
JDK-5045582 (opens in a new tab) in the jdk bug tracker:
binarySearchfailing for arrays bigger than 2^30, reported in 2004 and fixed in java 6. ↩ -
Arrays.java (opens in a new tab) at jdk-27-ga:
binarySearch0for ints, with(low + high) >>> 1and-(low + 1)for a missing key. ↩ ↩2 -
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 -
bisect.py (opens in a new tab) in cpython 3.15.0, whose
bisect_leftis the lower bound withmid = (lo + hi) // 2. a c version (opens in a new tab) replaces it when it’s available, and casts tosize_tbefore adding so the sum can’t overflow. ↩ ↩2 ↩3 -
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 < 5for the lower bound andx <= numfor the spot after the last copy. ↩ -
stdlib-bsearch.h (opens in a new tab) in glibc 2.42:
bsearchhalves a count instead of keeping two indexes, and returns as soon as the comparison says equal. ↩ -
partitioningIndex(where:) (opens in a new tab) in swift-algorithms 1.2.1. ↩
-
git bisect (opens in a new tab) in the git docs. ↩