sort-steps 0.2.4

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

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

/// Sorts a slice of data using the [bubble sort](https://en.wikipedia.org/wiki/Bubble_sort) in `O(n^2)`.
///
/// # Examples
///
/// ```
/// # use sort_steps::bubble_sort;
/// let numbers = [5, 9, 3, 6, 8, 2, 1, 7, 4];
/// println!("Bubble Sort Steps:");
/// for (i, v) in bubble_sort(&numbers).enumerate() {
///     println!("#{:02}: {:?}", i, v);
/// }
/// ```
pub fn bubble_sort<T>(v: &[T]) -> impl Iterator<Item = Vec<T>>
where
    T: PartialOrd + Clone,
{
    bubble_sort_by(v, |a, b| a.partial_cmp(b))
}

/// Sorts a slice of data using the [bubble sort](https://en.wikipedia.org/wiki/Bubble_sort) with a custom comparator.
///
/// # Examples
///
/// ```
/// # use sort_steps::bubble_sort_by;
/// let numbers = [5, 9, 3, 6, 8, 2, 1, 7, 4];
/// println!("Bubble Sort Steps:");
/// for (i, v) in bubble_sort_by(&numbers, |a, b| a.partial_cmp(b)).enumerate() {
///     println!("#{:02}: {:?}", i, v);
/// }
/// ```
pub fn bubble_sort_by<T, F>(v: &[T], compare: F) -> impl Iterator<Item = Vec<T>>
where
    F: Fn(&T, &T) -> Option<Ordering> + Copy,
    T: Clone,
{
    let mut n = v.len();
    let mut state = v.to_vec();
    let mut swapped = true;

    from_generator(move || {
        yield state.to_vec();
        while swapped {
            swapped = false;
            for i in 1..n {
                if gt_by(&state[i - 1], &state[i], compare) {
                    state.swap(i - 1, i);
                    swapped = true;
                    yield state.to_vec()
                }
            }
            n = n - 1;
        }
    })
}