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
/// 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 counting_sort(mut data: Vec<usize>, min: usize, max: usize) -> Vec<usize> {
    // create and fill counting bucket with 0
    let mut count: Vec<usize> = Vec::with_capacity(data.len());
    count.resize(data.len(), 0);

    for num in &data {
        count[num - min] = count[num - min] + 1;
    }
    let mut z: usize = 0;
    for i in min..max + 1 {
        while count[i - min] > 0 {
            data[z] = i;
            z += 1;
            count[i - min] = count[i - min] - 1;
        }
    }

    data
}

#[test]
fn test() {
    let arr1 = vec![1, 0, 2, 9, 3, 8, 4, 7, 5, 6];
    println!("{:?}", counting_sort(arr1, 0, 9));

    let arr2 = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    println!("{:?}", counting_sort(arr2, 0, 9));

    let arr3 = vec![10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0];
    println!("{:?}", counting_sort(arr3, 0, 10));
}