Skip to content

Instantly share code, notes, and snippets.

@romfrolov
Last active November 9, 2019 22:56
Show Gist options
  • Save romfrolov/aee204ab68b174f48bb0d57980236078 to your computer and use it in GitHub Desktop.
Save romfrolov/aee204ab68b174f48bb0d57980236078 to your computer and use it in GitHub Desktop.
Bubble sort in Rust.
fn bubble_sort(mut array: Vec<isize>) -> Vec<isize> {
let mut swapped: bool;
loop {
swapped = false;
for i in 0..array.len() - 1 {
if array[i] > array[i + 1] {
let temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
swapped = true;
}
}
if !swapped {
break;
}
}
array
}
#[test]
fn test() {
let unsorted_array = vec![3, 0, 2, 5, -1, 4, 1];
let expected_array = vec![-1, 0, 1, 2, 3, 4, 5];
let sorted_array = bubble_sort(unsorted_array);
assert_eq!(sorted_array, expected_array);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment