|
|
|
@ -10,11 +10,11 @@ include!("../include/include.rs");
|
|
|
|
|
// 简单实现,无法用于排序对象
|
|
|
|
|
fn counting_sort_naive(nums: &mut [i32]) {
|
|
|
|
|
// 1. 统计数组最大元素 m
|
|
|
|
|
let m = *nums.into_iter().max().unwrap();
|
|
|
|
|
let m = *nums.iter().max().unwrap();
|
|
|
|
|
// 2. 统计各数字的出现次数
|
|
|
|
|
// counter[num] 代表 num 的出现次数
|
|
|
|
|
let mut counter = vec![0; m as usize + 1];
|
|
|
|
|
for &num in &*nums {
|
|
|
|
|
for &num in nums.iter() {
|
|
|
|
|
counter[num as usize] += 1;
|
|
|
|
|
}
|
|
|
|
|
// 3. 遍历 counter ,将各元素填入原数组 nums
|
|
|
|
@ -31,16 +31,16 @@ fn counting_sort_naive(nums: &mut [i32]) {
|
|
|
|
|
// 完整实现,可排序对象,并且是稳定排序
|
|
|
|
|
fn counting_sort(nums: &mut [i32]) {
|
|
|
|
|
// 1. 统计数组最大元素 m
|
|
|
|
|
let m = *nums.into_iter().max().unwrap();
|
|
|
|
|
let m = *nums.iter().max().unwrap() as usize;
|
|
|
|
|
// 2. 统计各数字的出现次数
|
|
|
|
|
// counter[num] 代表 num 的出现次数
|
|
|
|
|
let mut counter = vec![0; m as usize + 1];
|
|
|
|
|
for &num in &*nums {
|
|
|
|
|
let mut counter = vec![0; m + 1];
|
|
|
|
|
for &num in nums.iter() {
|
|
|
|
|
counter[num as usize] += 1;
|
|
|
|
|
}
|
|
|
|
|
// 3. 求 counter 的前缀和,将“出现次数”转换为“尾索引”
|
|
|
|
|
// 即 counter[num]-1 是 num 在 res 中最后一次出现的索引
|
|
|
|
|
for i in 0..m as usize {
|
|
|
|
|
for i in 0..m {
|
|
|
|
|
counter[i + 1] += counter[i];
|
|
|
|
|
}
|
|
|
|
|
// 4. 倒序遍历 nums ,将各元素填入结果数组 res
|
|
|
|
@ -53,9 +53,7 @@ fn counting_sort(nums: &mut [i32]) {
|
|
|
|
|
counter[num as usize] -= 1; // 令前缀和自减 1 ,得到下次放置 num 的索引
|
|
|
|
|
}
|
|
|
|
|
// 使用结果数组 res 覆盖原数组 nums
|
|
|
|
|
for i in 0..n {
|
|
|
|
|
nums[i] = res[i];
|
|
|
|
|
}
|
|
|
|
|
nums.copy_from_slice(&res)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/* Driver Code */
|
|
|
|
|