Last active
November 25, 2018 14:54
-
-
Save ElectricCoffee/45c6ab365a7e3fe5f6f2132a596d7993 to your computer and use it in GitHub Desktop.
Rust implementations of all the algorithms found in the book "Grokking Algorithms"
This file contains hidden or 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
//! Chapter 1: Introduction to Algorithms. Binary Search. | |
// NB: input must be sorted | |
fn binary_search<T>(lst: &[T], item: &T) -> Option<usize> | |
where T: PartialEq + PartialOrd | |
{ | |
let mut low = 0; | |
let mut high = lst.len() - 1; | |
while low <= high { | |
let mid = low + high; | |
let guess = &lst[mid]; | |
if guess == item { | |
return Some(mid); | |
} | |
if guess > item { | |
high = mid - 1; | |
} else { | |
low = mid + 1; | |
} | |
} | |
None | |
} | |
fn main() { | |
let mut v = vec!["foo", "bar", "baz", "quux", "bing"]; | |
let q = v.clone(); | |
v.sort(); | |
for s in q.iter() { | |
println!("Looking for {}", s); | |
if let Some(idx) = binary_search(&v, s) { | |
println!("{} was found at index {}", v[idx], idx); | |
} else { | |
println!("Item could not be found"); | |
} | |
} | |
} |
This file contains hidden or 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
//! Chapter 2: Selection Sort. | |
fn find_smallest<T>(arr: &[T]) -> usize | |
where | |
T: PartialEq + PartialOrd, | |
{ | |
let mut smallest = &arr[0]; | |
let mut smallest_index = 0; | |
for i in 1..arr.len() { | |
if arr[i] < *smallest { | |
smallest = &arr[i]; | |
smallest_index = i; | |
} | |
} | |
smallest_index | |
} | |
fn selection_sort<T>(arr: &[T]) -> Vec<T> | |
where | |
T: PartialEq + PartialOrd + Clone, | |
{ | |
let mut arr = arr.to_vec(); // ensures the original won't get destroyed | |
let mut new_arr = Vec::new(); | |
for _ in 0..arr.len() { | |
let smallest = find_smallest(&arr); | |
new_arr.push(arr.remove(smallest)) | |
} | |
new_arr | |
} | |
fn main() { | |
let v = vec!["foo", "bar", "baz", "quux", "bing"]; | |
let new_v = selection_sort(&v); | |
println!("old: {:?}\nnew: {:?}", v, new_v) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment