binary_search
fn binary_search(Vec<int> xs, int needle) -> Option<int> Import
Source: use collections::vec::{binary_search}; src/collections/vec.hy Finds needle in the ascending vector xs by halving, and returns an index holding it.
xs must be sorted (collections::sort does that); on an unsorted vector the
result is unreliable. With duplicates, any matching index may be returned.
Parameters#
| Name | Type |
|---|---|
xs | Vec<int> |
needle | int |
Returns#
Option<int>
Contracts#
Checked according to --contracts (see Contracts).
ensures found_at(xs, needle, result)
Examples#
use collections::vec::{binary_search};
use tests::assert;
let xs: Vec<int> = [1, 3, 5, 7, 9];
assert!((binary_search(xs, 7) ?? -1) == 3);
assert!(binary_search(xs, 4).is_none());
See also#
collections::sortfold_int: The same asfold; kept for older code.contains: Returnstruewhenneedleis inxs.index_of: Returns the index of the firstneedleinxs, or-1.dedup: Returnsxswith runs of equal neighbours collapsed to one value.map: Returns a new vector withmapperapplied to each element, in order.filter: Returns the elements for whichpredistrue, in order.first: Returns the first element, orNonewhenxsis empty.