learn_rust_with_bubble_sort/
lib.rs1pub fn bubble_sort<T: PartialOrd + Clone>(collection: &[T]) -> Vec<T> {
14 let mut result: Vec<T> = collection.into();
15 for _ in 0..result.len() {
16 let mut swaps = 0;
17 for i in 1..result.len() {
18 if result[i - 1] > result[i] {
19 result.swap(i - 1, i);
20 swaps += 1;
21 }
22 }
23 if swaps == 0 {
24 break;
25 }
26 }
27 result
28}
29
30#[cfg(test)]
31mod tests {
32 use super::bubble_sort;
33 #[test]
34 fn test_bubble_sort() {
35 assert_eq!(bubble_sort(&vec![9, 8, 7, 6]), vec![6, 7, 8,
36 9]);
37 assert_eq!(bubble_sort(&vec![9_f32, 8_f32, 7_f32, 6_f32]),
38 vec!
39 [6_f32, 7_f32, 8_f32, 9_f32]);
40
41 assert_eq!(bubble_sort(&vec!['c','f','a','x']), vec!['a',
42 'c', 'f', 'x']);
43
44 assert_eq!(bubble_sort(&vec![6, 8, 7, 9]), vec![6, 7, 8,
45 9]);
46 assert_eq!(bubble_sort(&vec![2, 1, 1, 1, 1]), vec![1, 1, 1,
47 1, 2]);
48 }
49}