Skip to content

Instantly share code, notes, and snippets.

@jakejscott
Last active August 29, 2015 14:08
Show Gist options
  • Save jakejscott/3a1337084e9d97bc579f to your computer and use it in GitHub Desktop.
Save jakejscott/3a1337084e9d97bc579f to your computer and use it in GitHub Desktop.
Rust Bubble sort
fn main() {
let mut list = [1u, 5, 2, 7, 3, 9, 4, 6, 8];
bubble_sort(list);
println!("After sort: {}", list.as_slice());
let mut list = ['a', 'z', 'd', 'e', 'x', 'a'];
bubble_sort(list);
println!("After sort: {}", list.as_slice());
}
fn bubble_sort<T: Ord + Clone>(list: &mut[T]) {
let mut made_changes = true;
let mut item_count = list.len();
while made_changes {
made_changes = false;
item_count -= 1;
let mut i = 0;
while i < item_count {
if list[i] > list[i + 1] {
list.swap(i, i + 1);
made_changes = true;
}
i += 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment