Skip to content

Instantly share code, notes, and snippets.

@ElectricCoffee
Last active November 25, 2018 14:54
Show Gist options
  • Save ElectricCoffee/45c6ab365a7e3fe5f6f2132a596d7993 to your computer and use it in GitHub Desktop.
Save ElectricCoffee/45c6ab365a7e3fe5f6f2132a596d7993 to your computer and use it in GitHub Desktop.
Rust implementations of all the algorithms found in the book "Grokking Algorithms"
//! 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");
}
}
}
//! 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