Skip to content

Instantly share code, notes, and snippets.

@StephanieSunshine
Created December 7, 2021 12:46
Show Gist options
  • Save StephanieSunshine/ed6e45b8b5108eeab5def8c9df4deff6 to your computer and use it in GitHub Desktop.
Save StephanieSunshine/ed6e45b8b5108eeab5def8c9df4deff6 to your computer and use it in GitHub Desktop.
Bubblesort in Rust
// function: is_sorted
// input: uint32 list
// output: boolean
// a list is only sorted if the next neighbor in the list is greater. This is a test for that
fn is_sorted(l: &mut Vec<u32>) -> bool {
// This is called an anonymous dead mans switch it is meant to fail-deadly if there is a failure in logic
// ( our conditional is met ) we start out with high hopes that we will find nothing to trigger
// its failure and return true if we make it all the way through without returning false first
// Because our conditional looks one ahead, we must stop two before the finish line. We use a
// range here instead of a iterator so we can address the vectors elements directly
for e in 0..(*l).len()-1 {
// if the current element is greater than the next element, we have failed
if (*l)[e] > (*l)[e+1] {
// return our failure, we can break early after we find one in the name of speed
return false;
}
}
true
}
// function: bubblesort
// input: uint32 list
// output: uint32 list
// implement a bubble sort over a list of uint32 in Rust
fn bubblesort(l: &mut Vec<u32>) -> &mut Vec<u32> {
// while the list isn't sorted
while !is_sorted(l) {
// traverse the list
for e in 0..(*l).len()-1 {
// if the current one is greater than the next one, swap
if (*l)[e] > (*l)[e+1] {
// to swap, we must make a temp holder for one of the elements
let s = (*l)[e];
// swap the element you saved for the other element
(*l)[e] = (*l)[e+1];
// set the other element to the temp holder
(*l)[e+1] = s;
}
}
// at the end of each traversal, print the list
println!("{:?}", (*l));
}
// return the list
l
}
fn main() {
let mut list: Vec<u32> = Vec::new();
list.push(20);
list.push(40);
list.push(10);
list.push(50);
list.push(5);
list.push(1);
println!("{:?}", list);
println!("{:?}", bubblesort(&mut list));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment