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
pub fn counting_sort<F, T>(arr: &mut [T], min: usize, max: usize, key: F)
where
F: Fn(&T) -> usize,
T: Clone,
{
let mut prefix_sums = {
let len = max - min;
let mut count_arr = Vec::with_capacity(len);
count_arr.resize(len, 0);
for value in arr.iter() {
count_arr[key(value)] += 1;
}
count_arr
.into_iter()
.scan(0, |state, x| {
*state += x;
Some(*state - x)
})
.collect::<Vec<usize>>()
};
for value in arr.to_vec().iter() {
let index = key(value);
arr[prefix_sums[index]] = value.clone();
prefix_sums[index] += 1;
}
}
#[cfg(test)]
mod base {
use super::*;
fn counting_sort_(arr: &mut [i32]) {
counting_sort(arr, 1, 10, |int| *int as usize);
}
base_cases!(counting_sort_);
}
#[cfg(test)]
mod stability {
use super::*;
fn counting_sort_(arr: &mut [(i32, i32)]) {
counting_sort(arr, 1, 10, |t| t.0 as usize);
}
stability_cases!(counting_sort_);
}