1// ===== 计数排序 =====
2function countingSort(nums) {
3 const max = Math.max(...nums);
4 const count = new Array(max + 1).fill(0);
5 for (const x of nums) count[x]++;
6 for (let i = 1; i <= max; i++) count[i] += count[i - 1];
7 const out = new Array(nums.length);
8 for (let i = nums.length - 1; i >= 0; i--)
9 out[--count[nums[i]]] = nums[i];
10 return out;
11}
12// ===== 桶排序 =====
13function bucketSort(nums, bucketSize) {
14 const min = Math.min(...nums), max = Math.max(...nums);
15 const n = Math.floor((max - min) / bucketSize) + 1;
16 const buckets = Array.from({ length: n }, () => []);
17 for (const x of nums)
18 buckets[Math.floor((x - min) / bucketSize)].push(x);
19 const out = [];
20 for (const b of buckets)
21 out.push(...b.sort((a, b) => a - b));
22 return out;
23}
24// ===== 基数排序 (LSD) =====
25function radixSort(nums) {
26 const max = Math.max(...nums);
27 for (let exp = 1; Math.floor(max / exp) > 0; exp *= 10) {
28 const count = new Array(10).fill(0);
29 for (const x of nums) count[Math.floor(x / exp) % 10]++;
30 for (let i = 1; i < 10; i++) count[i] += count[i - 1];
31 const out = new Array(nums.length);
32 for (let i = nums.length - 1; i >= 0; i--)
33 out[--count[Math.floor(nums[i] / exp) % 10]] = nums[i];
34 nums = out;
35 }
36 return nums;
37}