-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path2-jump_search.rs
59 lines (45 loc) · 1.36 KB
/
2-jump_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
// Jump Search
mod search {
use std::cmp;
/// Find if the provided value is contained in the
/// provided vector of values via jump search.
///
// Complexity: O(sqrt(values.len()))
///
/// The vector values is expected to be in sorted order.
pub fn jump_search(values: &Vec<i32>, value: i32) -> bool {
if values.len() == 0 {
return false;
}
let jump: usize = (values.len() as f32).sqrt() as usize + 1;
let mut index: usize = 0;
while index < values.len() {
if values[index] == value {
return true;
}
if values[index] > value {
break;
}
index = cmp::min(index + jump, values.len());
}
let mut offset: usize = 1;
while offset < jump && offset <= index {
if values[index - offset] == value {
return true;
}
offset = offset + 1;
}
return false;
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_jump_search() {
assert!(crate::search::jump_search(&vec![-2, 0, 2, 3, 7, 24], 3));
}
#[test]
fn test_jump_search_negative() {
assert!(!crate::search::jump_search(&vec![-2, 0, 2, 3, 7, 24], 4));
}
}