sort-steps 0.2.4

Sort terms step by step.
Documentation
use crate::utils::lt_by;

use std::{cmp::Ordering, iter::from_generator};

/// Sorts a slice of data using the heap sort algorithm with a custom comparator.
///
/// # Examples
///
/// ```
/// # use sort_steps::{selection_sort};
/// let numbers = [5, 9, 3, 6, 8, 2, 1, 7, 4];
/// println!("Heap Sort Steps:");
/// for (i, v) in selection_sort(&numbers).enumerate() {
///     println!("#{:02}: {:?}", i, v);
/// }
/// ```
pub fn selection_sort<T>(v: &[T]) -> impl Iterator<Item = Vec<T>>
where
    T: PartialOrd + Clone,
{
    selection_sort_by(v, |a, b| a.partial_cmp(b))
}

/// Sorts a slice of data using the heap sort algorithm with a custom comparator.
///
/// # Examples
///
/// ```
/// # use sort_steps::{selection_sort_by};
/// let numbers = [5, 9, 3, 6, 8, 2, 1, 7, 4];
/// println!("Heap Sort Steps:");
/// for (i, v) in selection_sort_by(&numbers, |a, b| a.partial_cmp(b)).enumerate() {
///     println!("#{:02}: {:?}", i, v);
/// }
/// ```
pub fn selection_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();
    // Iterate through the vector
    from_generator(move || {
        yield state.to_vec();
        for i in 0..n {
            // Find the index of the minimum element
            let mut min_index = i;
            for j in (i + 1)..state.len() {
                if lt_by(&state[j], &state[min_index], compare) {
                    min_index = j;
                }
            }
            state.swap(i, min_index);
            yield state.to_vec();
        }
    })
}