Skip to main content

Algod/sorting/
insertion_sort.rs

1use std::cmp;
2
3/// Sorts a mutable slice using in-place insertion sort algorithm.
4///
5/// Time complexity is `O(n^2)`, where `n` is the number of elements.
6/// Space complexity is `O(1)` as it sorts elements in-place.
7pub fn insertion_sort<T>(arr: &mut [T])
8where
9    T: cmp::PartialOrd + Copy,
10{
11    for i in 1..arr.len() {
12        let cur = arr[i];
13        let mut j = i - 1;
14
15        while arr[j] > cur {
16            arr.swap(j + 1, j);
17            if j == 0 {
18                break;
19            }
20            j -= 1;
21        }
22    }
23}
24
25#[cfg(test)]
26mod tests {
27    use super::super::is_sorted;
28    use super::*;
29
30    #[test]
31    fn empty() {
32        let mut arr: [u8; 0] = [];
33        insertion_sort(&mut arr);
34        assert!(is_sorted(&arr));
35    }
36
37    #[test]
38    fn one_element() {
39        let mut arr: [char; 1] = ['a'];
40        insertion_sort(&mut arr);
41        assert!(is_sorted(&arr));
42    }
43
44    #[test]
45    fn already_sorted() {
46        let mut arr: [&str; 3] = ["a", "b", "c"];
47        insertion_sort(&mut arr);
48        assert!(is_sorted(&arr));
49    }
50
51    #[test]
52    fn basic() {
53        let mut arr: [&str; 4] = ["d", "a", "c", "b"];
54        insertion_sort(&mut arr);
55        assert!(is_sorted(&arr));
56    }
57
58    #[test]
59    fn odd_number_of_elements() {
60        let mut arr: Vec<&str> = vec!["d", "a", "c", "e", "b"];
61        insertion_sort(&mut arr);
62        assert!(is_sorted(&arr));
63    }
64
65    #[test]
66    fn repeated_elements() {
67        let mut arr: Vec<usize> = vec![542, 542, 542, 542];
68        insertion_sort(&mut arr);
69        assert!(is_sorted(&arr));
70    }
71}