Created
September 12, 2018 14:56
-
-
Save rylev/be8bdfe62a2fe45d3837551531af96ab to your computer and use it in GitHub Desktop.
Bubble Sort In Rust
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 sortable: [i32; 5] = [5, 8, 2, 7, 6]; | |
let length = sortable.len(); | |
let mut swapped = true; | |
print_array(&sortable); | |
while swapped { | |
swapped = false; | |
for i in 1..length { | |
let previous_element = sortable[i - 1]; | |
let current_element = sortable[i]; | |
if previous_element > current_element { | |
sortable.swap(i - 1, i); | |
swapped = true; | |
} | |
} | |
} | |
print_array(&sortable); | |
} | |
fn print_array<T: std::fmt::Display>(array: &[T]) { | |
print!("["); | |
for (i, elem) in array.iter().enumerate() { | |
print!("{}", elem); | |
if i != array.len() - 1 { | |
print!(","); | |
} | |
} | |
println!("]"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It was very helpful, thanks.