bubble_sort_scala/
lib.rs

1//! This is a non-optimized implementation of the [bubble sort] algorithm for the book Rust Cookbook by Packt. This implementation also clones the input vector.
2//!
3//! # Examples
4//!```
5//!# use bubble_sort::bubble_sort;
6//! let v = vec![2, 2, 10, 1, 5, 4, 3];
7//! assert_eq!(bubble_sort(&v), vec![1, 2, 2, 3, 4, 5, 10]);
8//!```
9
10///
11/// See module level documentation.
12///
13pub 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
34    #[test]
35    fn test_bubble_sort() {
36        assert_eq!(bubble_sort(&vec![9, 8, 7, 6]), vec![6, 7, 8, 9]);
37        assert_eq!(
38            bubble_sort(&vec![9_f32, 8_f32, 7_f32, 6_f32]),
39            vec![6_f32, 7_f32, 8_f32, 9_f32]
40        );
41
42        assert_eq!(
43            bubble_sort(&vec!['c', 'f', 'a', 'x']),
44            vec!['a', 'c', 'f', 'x']
45        );
46
47        assert_eq!(bubble_sort(&vec![6, 8, 7, 9]), vec![6, 7, 8, 9]);
48        assert_eq!(bubble_sort(&vec![2, 1, 1, 1, 1]), vec![1, 1, 1, 1, 2]);
49    }
50}