Skip to main content

lib_jsl_sorting/
shells_method.rs

1//! Shell's method.
2//!
3//! See the book entry [Comparison sorting](https://jwkunz.github.io/lib_jsl/book/sorting/comparison-sorts.html#shells-method).
4
5/// Sorts a slice using Shell's method with Ciura's gap sequence extended by a factor of 2.25.
6// ANCHOR: shell
7pub fn shell_sort<T: Ord>(slice: &mut [T]) {
8    let n = slice.len();
9    let mut gaps: Vec<usize> = vec![1, 4, 10, 23, 57, 132, 301, 701];
10    while *gaps.last().unwrap() < n {
11        let next = (*gaps.last().unwrap() as f64 * 2.25) as usize;
12        gaps.push(next);
13    }
14    for &gap in gaps.iter().rev() {
15        if gap >= n {
16            continue;
17        }
18        for i in gap..n {
19            let mut j = i;
20            while j >= gap && slice[j - gap] > slice[j] {
21                slice.swap(j - gap, j);
22                j -= gap;
23            }
24        }
25    }
26}
27// ANCHOR_END: shell
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32
33    #[test]
34    fn sorts() {
35        let mut v: Vec<i32> = (0..3000).map(|i| (i * 7919) % 1009 - 500).collect();
36        let mut expected = v.clone();
37        expected.sort();
38        shell_sort(&mut v);
39        assert_eq!(v, expected);
40    }
41
42    #[test]
43    fn edge_cases() {
44        let mut e: Vec<i32> = vec![];
45        shell_sort(&mut e);
46        let mut one = vec![3];
47        shell_sort(&mut one);
48        assert_eq!(one, vec![3]);
49    }
50}