Skip to content

Instantly share code, notes, and snippets.

@rylev
Created September 12, 2018 14:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rylev/be8bdfe62a2fe45d3837551531af96ab to your computer and use it in GitHub Desktop.
Save rylev/be8bdfe62a2fe45d3837551531af96ab to your computer and use it in GitHub Desktop.
Bubble Sort In Rust
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!("]");
}
@mhmtsnmzkanly
Copy link

It was very helpful, thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment