Skip to content

Commit 75bb349

Browse files
refactor: use ordering with cmp
1 parent 5704817 commit 75bb349

File tree

1 file changed

+11
-24
lines changed

1 file changed

+11
-24
lines changed

src/binary_search.rs

Lines changed: 11 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,22 @@
11
use std::cmp::Ordering;
22

3-
#[allow(dead_code)]
4-
fn binary_search<T>(items: Vec<T>, value: T) -> Option<usize>
3+
#[warn(dead_code)]
4+
fn binary_search<T>(list: Vec<T>, item: T) -> Option<usize>
55
where
66
T: std::cmp::Ord,
77
{
8-
if items.is_empty() {
9-
// Avoid running if no items are provided
8+
if list.is_empty() {
109
return None;
11-
}
12-
13-
let (mut start, mut end) = (0, items.len() - 1);
10+
};
11+
let (mut low, mut high) = (0, list.len() - 1);
1412

15-
loop {
16-
let idx = (start + end) / 2;
17-
let attempt = items.get(idx).unwrap();
18-
19-
if start > end {
20-
break;
21-
}
13+
while low <= high {
14+
let mid = (low + high) / 2;
2215

23-
match attempt.cmp(&value) {
24-
Ordering::Greater => {
25-
end = idx - 1;
26-
}
27-
Ordering::Less => {
28-
start = idx + 1;
29-
}
30-
Ordering::Equal => {
31-
return Some(idx);
32-
}
16+
match list[mid].cmp(&item) {
17+
Ordering::Greater => high = mid,
18+
Ordering::Less => low = mid + 1,
19+
Ordering::Equal => return Some(mid),
3320
}
3421
}
3522

0 commit comments

Comments
 (0)