# binary search

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

source: https://learning.anthnydas.com/algos/binary-search/

## tl;dr

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

## 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:

> **interactive figure:** 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.

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.

look in the middle. index 6 holds 27, smaller than 44. the array is sorted, so everything left of it is smaller too. lo jumps past mid, to 7.

the middle of 7 to 12 is 9, and it holds 44. that's big enough, so it may be the answer. hi stops on it, at 9, and 10 and 11 drop out.

the middle of 7 to 9 is 8, and it holds 36: too small. lo moves to 9 and meets hi. nothing is left in play.

lo = hi = 9 is the first item that's at least 44, and it holds 44: found, after 3 looks. a scan from the left looks at 10. a million items take 20 looks at most.

## 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.

> **interactive figure:** 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

> **interactive figure:** 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

```text
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

> **interactive figure:** 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 `lo` is smaller than `x`
- everything from `hi` on is at least `x`
- in between, `lo` up to `hi`, 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.[^go]

### 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 - 1` would throw the answer away
- `lo = mid` instead of `mid + 1` can loop forever. with `lo = 3` and `hi = 4`, mid is 3, and if `a[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.binarySearch` had 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.[^bloch][^jdk]
- `lo + (hi - lo) / 2` never 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.[^java] go converts the sum to an unsigned int before its shift, with a comment saying why.[^gosearch] cpython's c version casts to `size_t`[^python]
- python's own ints never wrap, so the plain `(lo + hi) // 2` in `bisect.py` is safe there[^python]

## complexity

> **interactive figure:** 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 `x` is
- 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.

`go/algos/binarysearch/binarysearch.go`

```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`

```rust
//! 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`

```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`

```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`

```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`

```python
"""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:

- **python.** `bisect.bisect_left` and `bisect_right` are the lower and upper bound[^python]
- **go.** `slices.BinarySearch` returns the lower bound and whether `x` is there.[^go] `sort.Search(n, f)` takes the yes or no question as a function[^gosearch]
- **rust.** `partition_point` gives either bound. `binary_search` returns `Ok` with the index of a match, or `Err` with where `x` would go. with duplicates, it can return any of them, and it never stops early, so the loop runs the same number of times for every `x`[^rust]
- **java.** `Arrays.binarySearch` returns the index, or `-(where it would go) - 1` when `x` isn't there[^java]
- **c.** `bsearch` returns a pointer to a match, or `NULL`. it can't tell you where a missing item would go[^glibc]
- **swift.** the standard library has none. swift-algorithms adds `partitioningIndex(where:)`, the lower bound for any yes or no question[^swift]

## 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`, or `hi = len(a) - 1` with `hi = mid`. pick one and keep its rules
- `lo = mid` when `a[mid]` is too small: it loops forever once two items are left
- `(lo + hi) / 2` with 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.BinarySearch` checks for it by hand[^go]

## variants

- **lower and upper bound.** `upper_bound` swaps `<` for `<=` and lands just past the last copy. the copies of `x` sit 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's `partition_point` and swift-algorithms' `partitioningIndex` all 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 things[^bisect]
- **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 whether `x` falls 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) for `x` at index i
- **binary insertion sort.** [insertion sort](/algos/insertion-sort/) with a binary search for each item's spot: fewer comparisons, the same shifts
- **as a tree.** a [binary search tree](/ds/bst/) keeps the halving in its shape, so inserts stay cheap too

## practice

- [binary search](https://leetcode.com/problems/binary-search/): `contains`, on a sorted array
- [search insert position](https://leetcode.com/problems/search-insert-position/): the lower bound
- [find first and last position of element in sorted array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/): the lower and the upper bound
- [first bad version](https://leetcode.com/problems/first-bad-version/): git bisect in miniature
- [koko eating bananas](https://leetcode.com/problems/koko-eating-bananas/): search on the answer
- [search in rotated sorted array](https://leetcode.com/problems/search-in-rotated-sorted-array/): find the sorted half first

[^go]: [slices.BinarySearch](https://github.com/golang/go/blob/go1.27.3/src/slices/sort.go#L126-L143) 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.

[^gosearch]: [sort.Search](https://github.com/golang/go/blob/go1.27.3/src/sort/search.go#L58-L73) at go1.27.3, which computes its midpoint as `int(uint(i+j) >> 1)`, commented as a way to avoid overflow.

[^python]: [bisect.py](https://github.com/python/cpython/blob/v3.15.0/Lib/bisect.py#L74-L107) in cpython 3.15.0, whose `bisect_left` is the lower bound with `mid = (lo + hi) // 2`. a [c version](https://github.com/python/cpython/blob/v3.15.0/Modules/_bisectmodule.c#L255-L258) replaces it when it's available, and casts to `size_t` before adding so the sum can't overflow.

[^bloch]: joshua bloch, [nearly all binary searches and mergesorts are broken](https://research.google/blog/extra-extra-read-all-about-it-nearly-all-binary-searches-and-mergesorts-are-broken/), google research, 2006.

[^jdk]: [JDK-5045582](https://bugs.openjdk.org/browse/JDK-5045582) in the jdk bug tracker: `binarySearch` failing for arrays bigger than 2^30, reported in 2004 and fixed in java 6.

[^java]: [Arrays.java](https://github.com/openjdk/jdk/blob/jdk-27-ga/src/java.base/share/classes/java/util/Arrays.java#L1697-L1715) at jdk-27-ga: `binarySearch0` for ints, with `(low + high) >>> 1` and `-(low + 1)` for a missing key.

[^rust]: [slice::binary_search](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/mod.rs#L2860-L2871) at rust 1.99.1, whose docs say any one of several matches can come back. the [loop it runs](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/mod.rs#L2994-L3021) skips an early exit on purpose, so the number of passes depends only on the length. [partition_point](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/mod.rs#L4823-L4871) 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.

[^glibc]: [stdlib-bsearch.h](https://sourceware.org/git/?p=glibc.git;a=blob;f=bits/stdlib-bsearch.h;hb=glibc-2.42) in glibc 2.42: `bsearch` halves a count instead of keeping two indexes, and returns as soon as the comparison says equal.

[^swift]: [partitioningIndex(where:)](https://github.com/apple/swift-algorithms/blob/1.2.1/Sources/Algorithms/Partition.swift#L167-L206) in swift-algorithms 1.2.1.

[^bisect]: [git bisect](https://git-scm.com/docs/git-bisect) in the git docs.

## related

- https://learning.anthnydas.com/algos/big-o.md
- https://learning.anthnydas.com/ds/bst.md
- https://learning.anthnydas.com/algos/two-pointers.md
- https://learning.anthnydas.com/algos/insertion-sort.md
