Skip to content

Commit 3d40469

Browse files
authored
Merge pull request TheAlgorithms#177 from soul-catcher/master
Update Binary Search algorithm to be more Rust idiomatic.
2 parents 97250a9 + d13f3f2 commit 3d40469

File tree

1 file changed

+8
-20
lines changed

1 file changed

+8
-20
lines changed

src/searching/binary_search.rs

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,19 @@
1-
use std::cmp::{PartialEq, PartialOrd};
2-
3-
pub fn binary_search<T: PartialEq + PartialOrd>(item: &T, arr: &[T]) -> Option<usize> {
4-
if arr.is_empty() {
5-
return None;
6-
}
1+
use std::cmp::Ordering;
72

3+
pub fn binary_search<T: Ord>(item: &T, arr: &[T]) -> Option<usize> {
84
let mut left = 0;
9-
let mut right = arr.len() - 1;
5+
let mut right = arr.len();
106

117
while left < right {
128
let mid = left + (right - left) / 2;
139

14-
if &arr[mid] > item {
15-
right = mid - 1;
16-
} else if &arr[mid] < item {
17-
left = mid + 1;
18-
} else {
19-
left = mid;
20-
break;
10+
match item.cmp(&arr[mid]) {
11+
Ordering::Less => right = mid,
12+
Ordering::Equal => return Some(mid),
13+
Ordering::Greater => left = mid + 1,
2114
}
2215
}
23-
24-
if &arr[left] == item {
25-
Some(left)
26-
} else {
27-
None
28-
}
16+
None
2917
}
3018

3119
#[cfg(test)]

0 commit comments

Comments
 (0)