-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathradix-sort.js
41 lines (29 loc) · 984 Bytes
/
radix-sort.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const getDigit = (num, i) => {
return Math.floor(Math.abs(num) / Math.pow(10, i)) % 10;
}
const digitCount = (num) => {
if (num === 0) return 1;
return Math.floor(Math.log10(Math.abs(num))) + 1;
}
const mostDigits = (nums) => {
let maxDigits = 0;
for (let i = 0; i < nums.length; i++) {
maxDigits = Math.max(maxDigits, digitCount(nums[i]));
}
return maxDigits;
}
const radixSort = (nums) => {
let maxDigitCount = mostDigits(nums);
for (let k = 0; k < maxDigitCount; k++) {
let digitBuckets = Array.from({ length: 10 }, () => []);
for (let i = 0; i < nums.length; i++) {
let digit = getDigit(nums[i], k);
digitBuckets[digit].push(nums[i]);
}
nums = [].concat(...digitBuckets);
}
return nums;
}
console.log(radixSort([23, 345, 5467, 12, 2345, 9852]))
console.log(radixSort([100, -3, 2, 4, 6, 9, 1, 2, 5, 3, 23]))
console.log(radixSort([10, 53, 0, 34, 390, -2, 45]))