function countingSort(arr) {
const max = Math.max(...arr);
const count = new Array(max + 1).fill(0);
// 统计每个数字出现的次数
for (let num of arr) {
count[num]++;
}
// 创建结果数组
const result = [];
// 将计数数组中的数字按顺序放入结果数组
for (let i = 0; i < count.length; i++) {
while (count[i] > 0) {
result.push(i);
count[i]--;
}
}
return result;
}
// 示例
const arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
const sortedArr = countingSort(arr);
console.log(sortedArr); // 输出排序后的数组