-
Notifications
You must be signed in to change notification settings - Fork 72
/
linear_search.rs
49 lines (39 loc) · 1.08 KB
/
linear_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
use std::cmp::PartialEq;
pub fn linear_search<T: PartialEq>(item: &T, arr: &[T]) -> Option<usize> {
for (i, data) in arr.iter().enumerate() {
if item == data {
return Some(i);
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn search_strings() {
let index = linear_search(&"a", &vec!["a", "b", "c", "d", "google", "zoo"]);
assert_eq!(index, Some(0));
}
#[test]
fn search_ints() {
let index = linear_search(&4, &vec![1, 2, 3, 4]);
assert_eq!(index, Some(3));
let index = linear_search(&3, &vec![1, 2, 3, 4]);
assert_eq!(index, Some(2));
let index = linear_search(&2, &vec![1, 2, 3, 4]);
assert_eq!(index, Some(1));
let index = linear_search(&1, &vec![1, 2, 3, 4]);
assert_eq!(index, Some(0));
}
#[test]
fn not_found() {
let index = linear_search(&5, &vec![1, 2, 3, 4]);
assert_eq!(index, None);
}
#[test]
fn empty() {
let index = linear_search(&1, &vec![]);
assert_eq!(index, None);
}
}