Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b84fbf6

Browse files
feat: use cmp with ordering on binary search (#1)
* refactor: use ordering with cmp * fix: fmt issues
1 parent 5704817 commit b84fbf6

File tree

2 files changed

+12
-28
lines changed

2 files changed

+12
-28
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

‎src/dijkstras.rs‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,7 @@ impl<N> PartialEq for Visit<N> {
4141
impl<N> Eq for Visit<N> {}
4242

4343
#[allow(dead_code)]
44-
fn dijkstra<'a>(
45-
start: Node<'a>,
46-
graph: &WeightedGraph<'a>,
47-
) -> HashMap<Node<'a>, usize> {
44+
fn dijkstra<'a>(start: Node<'a>, graph: &WeightedGraph<'a>) -> HashMap<Node<'a>, usize> {
4845
let mut distances: HashMap<Node, usize> = HashMap::new();
4946
let mut visited: HashSet<Node> = HashSet::new();
5047
let mut to_visit: BinaryHeap<Visit<Node>> = BinaryHeap::new();

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /