1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
pub fn binary_search<T>(arr: &[T], target: &T) -> Result<usize, usize>
where
T: PartialOrd,
{
let mut size = arr.len();
if size == 0 {
return Err(0);
}
let mut base = 0_usize;
while size > 1 {
let half = size / 2;
let mid = base + half;
if arr[mid] <= *target {
base = mid
}
size -= half;
}
if arr[base] == *target {
Ok(base)
} else {
Err(base + (arr[base] < *target) as usize)
}
}
#[cfg(test)]
mod base {
use super::*;
sorted_no_duplicate_cases!(binary_search);
}