-
Notifications
You must be signed in to change notification settings - Fork 72
/
binary_search.rs
106 lines (85 loc) · 2.82 KB
/
binary_search.rs
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
use std::cmp::Ordering;
pub fn binary_search<T: Ord>(item: &T, arr: &[T]) -> Option<usize> {
let mut is_asc = true;
if arr.len() > 1 {
is_asc = arr[0] < arr[arr.len() - 1];
}
let mut left = 0;
let mut right = arr.len();
while left < right {
let mid = left + (right - left) / 2;
if is_asc {
match item.cmp(&arr[mid]) {
Ordering::Less => right = mid,
Ordering::Equal => return Some(mid),
Ordering::Greater => left = mid + 1,
}
} else {
match item.cmp(&arr[mid]) {
Ordering::Less => left = mid + 1,
Ordering::Equal => return Some(mid),
Ordering::Greater => right = mid,
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let index = binary_search(&"a", &vec![]);
assert_eq!(index, None);
}
#[test]
fn one_item() {
let index = binary_search(&"a", &vec!["a"]);
assert_eq!(index, Some(0));
}
#[test]
fn search_strings_asc() {
let index = binary_search(&"a", &vec!["a", "b", "c", "d", "google", "zoo"]);
assert_eq!(index, Some(0));
let index = binary_search(&"google", &vec!["a", "b", "c", "d", "google", "zoo"]);
assert_eq!(index, Some(4));
}
#[test]
fn search_strings_desc() {
let index = binary_search(&"a", &vec!["zoo", "google", "d", "c", "b", "a"]);
assert_eq!(index, Some(5));
let index = binary_search(&"zoo", &vec!["zoo", "google", "d", "c", "b", "a"]);
assert_eq!(index, Some(0));
let index = binary_search(&"google", &vec!["zoo", "google", "d", "c", "b", "a"]);
assert_eq!(index, Some(1));
}
#[test]
fn search_ints_asc() {
let index = binary_search(&4, &vec![1, 2, 3, 4]);
assert_eq!(index, Some(3));
let index = binary_search(&3, &vec![1, 2, 3, 4]);
assert_eq!(index, Some(2));
let index = binary_search(&2, &vec![1, 2, 3, 4]);
assert_eq!(index, Some(1));
let index = binary_search(&1, &vec![1, 2, 3, 4]);
assert_eq!(index, Some(0));
}
#[test]
fn search_ints_desc() {
let index = binary_search(&4, &vec![4, 3, 2, 1]);
assert_eq!(index, Some(0));
let index = binary_search(&3, &vec![4, 3, 2, 1]);
assert_eq!(index, Some(1));
let index = binary_search(&2, &vec![4, 3, 2, 1]);
assert_eq!(index, Some(2));
let index = binary_search(&1, &vec![4, 3, 2, 1]);
assert_eq!(index, Some(3));
}
#[test]
fn not_found() {
let index = binary_search(&5, &vec![1, 2, 3, 4]);
assert_eq!(index, None);
let index = binary_search(&5, &vec![4, 3, 2, 1]);
assert_eq!(index, None);
}
}