Skip to content

Instantly share code, notes, and snippets.

@aramperes
Created January 22, 2020 06:01
Show Gist options
  • Save aramperes/59587d0ea30f18d33ea21418a0aee991 to your computer and use it in GitHub Desktop.
Save aramperes/59587d0ea30f18d33ea21418a0aee991 to your computer and use it in GitHub Desktop.
Some sorting algorithms implemented in Rust, with tests
/// Some sorting algorithms written in Rust.
fn insertion_sort(vec: &mut Vec<i32>) {
let length: i32 = vec.len() as i32;
if length < 2 {
// Vector is already sorted if of length 0 or 1
return;
}
for n in 1..length {
let key = vec[n as usize];
let mut left_index = n - 1;
// Move 'key' to the left as long as the item to the left is bigger
while left_index >= 0 && vec[left_index as usize] > key {
vec[(left_index + 1) as usize] = vec[left_index as usize];
left_index -= 1;
}
// No need to move to the left anymore, set key to where it's supposed to be
vec[(left_index + 1) as usize] = key;
}
}
fn selection_sort(vec: &mut Vec<i32>) {
let length: i32 = vec.len() as i32;
if length < 2 {
// Vector is already sorted if of length 0 or 1
return;
}
for prefix_index in 0..length {
let prefix = vec[prefix_index as usize];
let mut current_minimum_index = prefix_index;
for suffix_index in (prefix_index + 1)..length {
// Find smallest element
let suffix = vec[suffix_index as usize];
if suffix < vec[current_minimum_index as usize] {
current_minimum_index = suffix_index;
}
}
// Swap the smallest element
vec[prefix_index as usize] = vec[current_minimum_index as usize];
vec[current_minimum_index as usize] = prefix;
}
}
fn bubble_sort(vec: &mut Vec<i32>) {
let length: i32 = vec.len() as i32;
if length < 2 {
// Vector is already sorted if of length 0 or 1
return;
}
for pass in 0..length {
// Each pass is from beginning to end, but excluding the rightmost increasingly
for right_index in 1..(length - pass) {
let left_index = right_index - 1;
// If the left is larger than the right, swap
let left = vec[left_index as usize];
let right = vec[right_index as usize];
if left > right {
vec[right_index as usize] = left;
vec[left_index as usize] = right;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn _test_case() -> (Vec<i32>, Vec<i32>) {
let unsorted: Vec<i32> = vec![4, 10, 5, 1, 2, 4, -2];
let sorted: Vec<i32> = vec![-2, 1, 2, 4, 4, 5, 10];
return (unsorted, sorted);
}
#[test]
fn test_insertion_sort() {
let (unsorted, sorted) = _test_case();
let mut to_sort: Vec<i32> = unsorted.clone();
insertion_sort(&mut to_sort);
assert_eq!(sorted, to_sort);
}
#[test]
fn test_selection_sort() {
let (unsorted, sorted) = _test_case();
let mut to_sort: Vec<i32> = unsorted.clone();
selection_sort(&mut to_sort);
assert_eq!(sorted, to_sort);
}
#[test]
fn test_bubble_sort() {
let (unsorted, sorted) = _test_case();
let mut to_sort: Vec<i32> = unsorted.clone();
bubble_sort(&mut to_sort);
assert_eq!(sorted, to_sort);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment