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
use crate::utils::gt_by;
use std::{cmp::Ordering, iter::from_generator};
/// Sorts a slice of data using the shell sort algorithm.
///
/// # Examples
///
/// ```
/// # use sort_steps::{shell_sort};
/// let numbers = [5, 9, 3, 6, 8, 2, 1, 7, 4];
/// println!("Shell Sort Steps:");
/// for (i, v) in shell_sort(&numbers).enumerate() {
/// println!("#{:02}: {:?}", i, v);
/// }
/// ```
pub fn shell_sort<T>(v: &[T]) -> impl Iterator<Item = Vec<T>>
where
T: PartialOrd + Clone,
{
shell_sort_by(v, |a, b| a.partial_cmp(b))
}
/// Sorts a slice of data using the shell sort algorithm with a custom comparator.
///
/// # Examples
///
/// ```
/// # use sort_steps::{shell_sort_by};
/// let numbers = [5, 9, 3, 6, 8, 2, 1, 7, 4];
/// println!("Shell Sort Steps:");
/// for (i, v) in shell_sort_by(&numbers, |a, b| a.partial_cmp(b)).enumerate() {
/// println!("#{:02}: {:?}", i, v);
/// }
/// ```
pub fn shell_sort_by<T, F>(v: &[T], compare: F) -> impl Iterator<Item = Vec<T>>
where
F: Fn(&T, &T) -> Option<Ordering> + Copy,
T: Clone,
{
let n = v.len();
let mut state = v.to_vec();
let mut gap = n / 2;
from_generator(move || {
yield state.to_vec();
while gap > 0 {
for i in gap..n {
let mut j = i;
let temp = state[i].clone();
while j >= gap && gt_by(&state[j - gap], &temp, compare) {
state[j] = state[j - gap].clone();
j -= gap;
// yield state.to_vec();
}
state[j] = temp;
yield state.to_vec();
}
gap /= 2;
}
})
}