std-method

slice::binary_search

Search an ascending sorted sequence. Ok contains a matching index; Err contains the insertion index that preserves ordering. Duplicate matches need not return the first occurrence. Expected stdout (not executed): Ok(1) Err(2) Common mistake: Calling binary_search on unsorted data or assuming a duplicate match is the first one.

Formal Syntax & Structure

rust syntaxrust
slice.binary_search(&target) -> Result<usize, usize>

Working Example

Example Snippetrust
fn main() {    let data = [10, 20, 40];    println!("{:?} {:?}", data.binary_search(&20), data.binary_search(&30));}
Rust Reference