- Published on
计数
- Authors

- Name
- 李丹秋
/* 计数排序 */
// 完整实现,可排序对象,并且是稳定排序
function countingSort(nums) {
// 1. 统计数组最大元素 m
let m = Math.max(...nums);
// 2. 统计各数字的出现次数
// counter[num] 代表 num 的出现次数
const counter = new Array(m + 1).fill(0);
for (const num of nums) {
counter[num]++;
}
// 3. 求 counter 的前缀和,将“出现次数”转换为“尾索引”
// 即 counter[num]-1 是 num 在 res 中最后一次出现的索引
for (let i = 0; i < m; i++) {
counter[i + 1] += counter[i];
}
// 4. 倒序遍历 nums ,将各元素填入结果数组 res
// 初始化数组 res 用于记录结果
const n = nums.length;
const res = new Array(n);
for (let i = n - 1; i >= 0; i--) {
const num = nums[i];
res[counter[num] - 1] = num; // 将 num 放置到对应索引处
counter[num]--; // 令前缀和自减 1 ,得到下次放置 num 的索引
}
// 使用结果数组 res 覆盖原数组 nums
for (let i = 0; i < n; i++) {
nums[i] = res[i];
}
}
let arr = [1,0,0,1,2,0,4,0,2,2,4]
console.log('排序前的数组: ', arr)
let sortedArr = countingSortNaive(arr)
console.log('排序后的数组: ', sortedArr)
计数排序只适用于非负整数。若想将其用于其他类型的数据,需要确保这些数据可以转换为非负整数,并且在转换过程中不能改变各个元素之间的相对大小关系。例如,对于包含负数的整数数组,可以先给所有数字加上一个常数,将全部数字转化为正数,排序完成后再转换回去。
计数排序适用于数据量大但数据范围较小的情况。比如,在上述示例中m不能太大,否则会占用过多空间。而当 n < m 时,计数排序使用O(m)时间,可能比O(nlogn)的排序算法还要慢。