Last active
August 29, 2015 14:08
-
-
Save jakejscott/3a1337084e9d97bc579f to your computer and use it in GitHub Desktop.
Rust Bubble sort
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
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