algorithms_rs/search/
binary_search.rs1pub fn search<T>(list: &[T], item: Option<&T>) -> Option<usize>
3where
4 T: core::cmp::PartialEq + core::cmp::PartialOrd,
5{
6 let mut low = 0usize;
7 let mut high = list.len(); while low < high {
11 let mid = (low + high) / 2;
12 let guess = list.get(mid);
13 if guess == item {
14 return Some(mid);
15 } else if guess > item {
16 high = mid - 1;
17 } else {
18 low = mid + 1;
19 }
20 }
21
22 None
23}
24
25#[test]
26fn test_binary_search() {
27 let list = vec![1];
28 let idx = search(&list, Some(&1));
29 println!("idx = {idx:?}");
30}