sort-steps 0.2.4

Sort terms step by step.
Documentation
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::{heap_sort};
/// let numbers = [5, 9, 3, 6, 8, 2, 1, 7, 4];
/// println!("Heap Sort Steps:");
/// for (i, v) in heap_sort(&numbers).enumerate() {
///     println!("#{:02}: {:?}", i, v);
/// }
/// ```
pub fn heap_sort<T>(v: &[T]) -> impl Iterator<Item = Vec<T>>
where
    T: PartialOrd + Clone,
{
    heap_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::{heap_sort_by};
/// let numbers = [5, 9, 3, 6, 8, 2, 1, 7, 4];
/// println!("Heap Sort Steps:");
/// for (i, v) in heap_sort_by(&numbers, |a, b| a.partial_cmp(b)).enumerate() {
///     println!("#{:02}: {:?}", i, v);
/// }
/// ```
pub fn heap_sort_by<T, F>(v: &[T], compare: F) -> impl Iterator<Item = Vec<T>>
where
    F: Fn(&T, &T) -> Option<Ordering> + Copy,
    T: Clone,
{
    // Implement heap sort and collect steps
    let mut state = v.to_vec();
    from_generator(move || {
        yield state.to_vec();
        build_max_heap(&mut state, compare);
        yield state.to_vec();
        for i in (1..state.len()).rev() {
            state.swap(0, i);
            yield state.to_vec();
            max_heapify(&mut state, 0, i, compare);
        }
    })
}

// Create a max heap from the input vector
fn build_max_heap<T, F>(v: &mut Vec<T>, compare: F)
where
    F: Fn(&T, &T) -> Option<Ordering> + Copy,
    T: Clone,
{
    let len = v.len();
    for i in (0..len / 2).rev() {
        max_heapify(v, i, len, compare);
    }
}

// Maintain the max heap property
fn max_heapify<T, F>(v: &mut Vec<T>, i: usize, heap_size: usize, compare: F)
where
    F: Fn(&T, &T) -> Option<Ordering> + Copy,
    T: Clone,
{
    let left = 2 * i + 1;
    let right = 2 * i + 2;
    let mut largest = i;

    if left < heap_size && compare(&v[left], &v[largest]) == Some(Ordering::Greater) {
        largest = left;
    }

    if right < heap_size && compare(&v[right], &v[largest]) == Some(Ordering::Greater) {
        largest = right;
    }

    if largest != i {
        v.swap(i, largest);
        max_heapify(v, largest, heap_size, compare);
    }
}