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.
Code
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
Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.