Skip to main content

binary_search

Function binary_search 

Source
pub fn binary_search<T: Ord>(arr: &[T], target: &T) -> Result<usize, Error>
Expand description

Binary search.

arr must be sorted in ascending order; this is a caller contract checked with debug_assert! in debug builds so searches stay O(log n). On unsorted input in release builds the result is unspecified (typically NotFound).

Returns Ok(index) of the target, or Err(Error::NotFound) if absent.

ยงExamples

use algorithms_lib::binary_search;
assert_eq!(binary_search(&[2, 4, 6, 8], &6), Ok(2));