rust_sort/
bubble_sort.rs

1use super::Sortable;
2
3/// Bubble sorts in-place, stable, in ascending order a mutable ref slice of type T: Sortable
4///
5/// Bubble sort continuously loops over elements in slice collection, swapping elements
6/// if they are out of order. If no swaps occur in a loop then the sort is complete.
7///
8/// # Examples
9///
10/// ```
11/// use rust_sort::bubble_sort::sort;
12///
13/// let mut arr = [3, 2, 1, 7, 9, 4, 1, 2];
14/// sort(&mut arr);
15/// assert_eq!(arr, [1, 1, 2, 2, 3, 4, 7, 9]);
16///
17/// ```
18pub fn sort<T: Sortable>(list: &mut [T]) {
19    let len = list.len();
20    if len <= 1 {
21        return;
22    }
23
24    loop {
25        let mut bubbled = false;
26        for i in 0..len - 1 {
27            if list[i] > list[i + 1] {
28                list.swap(i, i + 1);
29                bubbled = true;
30            }
31        }
32        if !bubbled {
33            break;
34        }
35    }
36}