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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use super::Sort;

/// Insert sort
#[derive(Debug)]
pub struct InsertSort<T> {
    arr: Vec<T>,
}

impl<T> InsertSort<T> {
    fn insert_sort<F>(&mut self, f: F)
    where
        F: FnOnce(&T, &T) -> bool + core::marker::Copy,
    {
        let len = self.arr.len();

        for i in 1..len {
            // do a[i] insert to a[i - 1], a[i - 2], a[i - 3]... among
            let mut j = i;
            while j > 0 && f(&self.arr[j], &self.arr[j - 1]) {
                self.arr.swap(j, j - 1);
                j -= 1;
            }
        }
    }
}
impl<T> From<Vec<T>> for InsertSort<T> {
    fn from(arr: Vec<T>) -> Self {
        Self { arr }
    }
}

impl<T: core::clone::Clone> From<&[T]> for InsertSort<T> {
    fn from(arr: &[T]) -> Self {
        Self { arr: arr.into() }
    }
}

impl<T: core::cmp::PartialOrd + Clone> Sort<T> for InsertSort<T> {
    fn inner(&self) -> Vec<T> {
        self.arr.clone()
    }

    fn sort_by<F>(&mut self, f: F)
    where
        F: FnOnce(&T, &T) -> bool + core::marker::Copy,
    {
        self.insert_sort(f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_insert_sort_ok() {
        let mut insert = InsertSort::from(vec![10, 9, 8, 6, 5, 4, 3, 2, 1]);
        println!("insert sort before: {insert:?}");
        insert.sort();
        println!("insert sort after: {insert:?}");
        assert!(insert.is_sort());
    }

    #[test]
    fn test_insert_sort_a_empty_arr() {
        let mut insert = InsertSort::from(Vec::<i32>::new());
        insert.sort();
        assert!(insert.is_sort());
    }
}