forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 1
/
bubble_sort.rs
45 lines (42 loc) · 935 Bytes
/
bubble_sort.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
pub fn bubble_sort<T: Ord>(arr: &mut [T]) {
if arr.is_empty() {
return;
}
let mut sorted = false;
let mut n = arr.len();
while !sorted {
sorted = true;
for i in 0..n - 1 {
if arr[i] > arr[i + 1] {
arr.swap(i, i + 1);
sorted = false;
}
}
n -= 1;
}
}
#[cfg(test)]
mod tests {
use super::super::is_sorted;
use super::*;
#[test]
fn descending() {
//descending
let mut ve1 = vec![6, 5, 4, 3, 2, 1];
bubble_sort(&mut ve1);
assert!(is_sorted(&ve1));
}
#[test]
fn ascending() {
//pre-sorted
let mut ve2 = vec![1, 2, 3, 4, 5, 6];
bubble_sort(&mut ve2);
assert!(is_sorted(&ve2));
}
#[test]
fn empty() {
let mut ve3: Vec<usize> = vec![];
bubble_sort(&mut ve3);
assert!(is_sorted(&ve3));
}
}