Created
August 8, 2017 11:28
-
-
Save luki/a4f20793506b012a3ca59f3dac002a21 to your computer and use it in GitHub Desktop.
Studying search algorithms, implementing them in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn linear_search<T: Ord>(vec: &Vec<T>, key: &T) -> Option<usize> { | |
let mut result: Option<usize> = None; | |
for (i, n) in vec.into_iter().enumerate() { | |
if n == key { | |
result = Some(i) | |
} | |
}; | |
result | |
} | |
// Binary Search Algorithm (Recursive implementation) | |
use std::ops::Range; | |
fn binary_search<T: Ord>(vec: &Vec<T>, key: &T, range: Range<usize>) -> Option<usize> { | |
if range.start >= range.end { | |
None | |
} else { | |
let mid_index = range.start + (range.end - range.end) / 2; | |
if &vec[mid_index] > key { | |
return binary_search(vec, key, (range.start..mid_index - 1)) | |
} else if &vec[mid_index] < key { | |
return binary_search(vec, key, (mid_index + 1..range.end)) | |
} else { | |
Some(mid_index) | |
} | |
} | |
} | |
fn main() { | |
// Linear Search Algorithm | |
let some_vec = vec!["Hello", "Hi"]; | |
match linear_search(&some_vec, &"Hi") { | |
Some(val) => println!("{}", val), | |
None => panic!("Oh!") | |
}; | |
// Binary Search Algorithm | |
let other_vec = vec![0, 5, 30, 66, 99, 130, 185, 230, 900]; | |
let range = 0..5; | |
match binary_search(&other_vec, &30, (0..other_vec.len() - 1)) { | |
Some(val) => println!("{}", val), | |
None => panic!("Couldn't find the value)") | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment