Binary search
Binary search finds a target in a sorted slice in O(log n) comparisons. Rust exposes it as slice::binary_search and the *_by / *_by_key variants.
Detailed Explanation
A linear scan is O(n). If the slice is sorted, you can look at the middle element and throw away half the range each step. That is binary search: O(log n) comparisons, O(1) extra space. The slice must already be ordered the same way the search compares, or you will get a silent wrong answer, not a panic.
xs.binary_search(&target) returns Ok(index) when target is present. If there are duplicates, the index is any one of them, not necessarily the first. Err(index) is the insertion point: where you would insert to keep the slice sorted. That Err is useful. You do not have to search again to splice.
binary_search_by takes a closure that returns Ordering. binary_search_by_key extracts a key. These are how you search a slice of structs by a field: sessions.binary_search_by_key(&user_id, |s| s.user_id) if the slice is sorted by user_id.
The invariant you must keep: xs[i] <= xs[j] for i < j under the same order. Sorting with sort_unstable then searching with a different by_key is a bug. If the data is a BTreeMap, you already have log n search and should not binary-search a collected Vec unless you have a reason.
Hand-writing the loop is a classic interview exercise and a classic source of off-by-one errors (mid = (lo + hi) / 2 overflow, hi = mid versus mid - 1). Prefer the standard method. If you write it, use lo + (hi - lo) / 2 and a clear invariant: xs[lo] <= target or the target is to the right, and so on.
When you reach for binary search: a sorted slice you will query many times. When you reach for a HashMap: unordered keys, O(1) average. When you reach for BTreeMap: you need the ordered map, not a snapshot slice.
Code Examples
fn main() {
let xs = [1, 3, 5, 7, 9];
println!("{:?}", xs.binary_search(&7)); // prints: Ok(3)
println!("{:?}", xs.binary_search(&6)); // prints: Err(3) — insert at 3 to keep sorted
let names = ["ada", "grace", "linus"];
println!("{:?}", names.binary_search(&"grace")); // prints: Ok(1)
}Common Gotchas
Unsorted input is a wrong answer, not a panic
The method assumes the slice is sorted. Test that assumption or sort first.
`Ok` with duplicates is any match
If you need the leftmost index, write a `partition_point` predicate: `xs.partition_point(|x| *x < target)`.
`Err(i)` is an insertion index
It is already the lower bound. Do not run a second search to find where to insert.
`(lo + hi) / 2` can overflow
The standard library does not. If you hand-roll, write `lo + (hi - lo) / 2`.