|
| 1 | +/// Counting sort |
| 2 | +
|
| 3 | +/// * `arr` - Collection of value to be sorted in place. |
| 4 | +
|
| 5 | +/// * `min` - Lower bound of the integer range. |
| 6 | +
|
| 7 | +/// * `max` - Upper bound of the integer range. |
| 8 | +
|
| 9 | +/// * `key` - Function extracting key witn the integer range from elements. |
| 10 | +
|
| 11 | +pub fn counting_sort<F, T>(arr: &mut [T], min: usize, max: usize, key: F) |
| 12 | +where |
| 13 | + F: Fn(&T) -> usize, |
| 14 | + T: Clone, |
| 15 | +{ |
| 16 | + let mut prefix_sums = { |
| 17 | + // 1. Initialize the count array with default value 0. |
| 18 | + let len = max - min; |
| 19 | + let mut count_arr = Vec::with_capacity(len); |
| 20 | + count_arr.resize(len, 0); |
| 21 | + |
| 22 | + // 2. Scan elements to collect counts. |
| 23 | + for value in arr.iter() { |
| 24 | + count_arr[key(value)] += 1; |
| 25 | + } |
| 26 | + |
| 27 | + // 3. Calculate prefix sum. |
| 28 | + count_arr |
| 29 | + .into_iter() |
| 30 | + .scan(0, |state, x| { |
| 31 | + *state += x; |
| 32 | + Some(*state - x) |
| 33 | + }) |
| 34 | + .collect::<Vec<usize>>() |
| 35 | + }; |
| 36 | + |
| 37 | + // 4. Use prefix sum as index position of output element. |
| 38 | + for value in arr.to_vec().iter() { |
| 39 | + let index = key(value); |
| 40 | + arr[prefix_sums[index]] = value.clone(); |
| 41 | + prefix_sums[index] += 1; |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +#[cfg(test)] |
| 46 | + |
| 47 | +mod base { |
| 48 | + use super::*; |
| 49 | + fn counting_sort_(arr: &mut [i32]) { |
| 50 | + counting_sort(arr, 1, 10, |int| *int as usize); |
| 51 | + } |
| 52 | + base_cases!(counting_sort_); |
| 53 | +} |
| 54 | + |
| 55 | +#[cfg(test)] |
| 56 | + |
| 57 | +mod stability { |
| 58 | + use super::*; |
| 59 | + fn counting_sort_(arr: &mut [(i32, i32)]) { |
| 60 | + counting_sort(arr, 1, 10, |t| t.0 as usize); |
| 61 | + } |
| 62 | + stability_cases!(counting_sort_); |
| 63 | +} |
0 commit comments