Binary Search Yields Ok Or Insertion Point

slice::binary_search returns Ok with the index on a hit and Err with the insertion point on a miss, which inserts a new element keeping order.

RustData Integrity

Code

rustsnippet
28 lines
fn main() {
    let sorted = [3, 8, 15, 15, 42, 100];

    // Hit: Ok carries the index (which duplicate is unspecified)
    for target in [8, 100] {
        match sorted.binary_search(&target) {
            Ok(index) => println!("{target} at index {index}"),
            Err(insert) => println!("{target} not found, insert at {insert}"),
        }
    }

    // Miss: Err carries the insertion point that keeps order - insert straight into it
    for target in [1, 50] {
        match sorted.binary_search(&target) {
            Ok(_) => unreachable!(),
            Err(insert) => {
                let mut grown = sorted.to_vec();
                grown.insert(insert, target);
                println!("{target} inserted at {insert}: {:?}", grown);
            }
        }
    }

    // The keyed binary_search_by: compares through a projection, e.g. finding strings by length
    let by_len = ["a", "bbb", "ccccc"];
    let hit = by_len.binary_search_by(|probe| probe.len().cmp(&3));
    println!("len-3 string: {:?}", by_len[hit.expect("present")]);
}

What the code does

Binary Search Yields Ok Or Insertion Point keeps everything in the function main.

The cycling part of this snippet is for target in [8, 100]. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Applying it

The demo output is labeled (len-3 string:), so every printed line maps back to its originating operation.

Statements that matter

Err(insert) => {
    let mut grown = sorted.to_vec();
    grown.insert(insert, target);
    println!("{target} inserted at {insert}: {:?}", grown);
}
match sorted.binary_search(&target) {
    Ok(index) => println!("{target} at index {index}"),
    Err(insert) => println!("{target} not found, insert at {insert}"),
}

Interactive Tools for This Topic

FAQ

What does Binary Search Yields Ok Or Insertion Point print when run?
Running the file directly is enough — expect labeled output lines such as `len-3 string:`.