function sortingCount(arr) {
let min = arr[0];
let max = arr[0];
const length = arr.length;
for (const item of arr) {
max = Math.max(max, item);
min = Math.min(min, item);
}
// step1: 计算出最大最小值的差
const distance = max - min;
// step2: 创建统计数组统计对应元素出现的次数
let countArr = new Array(distance + 1).fill(0);
// tips:为什么要算出最大最小值的差呢?因为需要保证统计数组的空间是刚刚好的,不被浪费
for (let i = 0; i < length; i++) {
countArr[arr[i] - min] += 1;
}
console.log('countArr', countArr);
// step3: 遍历统计数组,将每个元素按照顺序push到结果数组中
let res =[];
for (let i = 0; i < distance + 1; i++) {
while (countArr[i] > 0) {
// 这里的 i + min 才是真实的值。(我们存的是和min的差值)
res.push(i + min);
countArr[i] -= 1;
}
}
return res
}
console.log('sortingCount([2, 9, 6, 7, 4, 3, 1, 8])', sortingCount([2, 9, 6, 7, 4, 3, 1, 8]))
console