-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17. Radix Sort.js
More file actions
36 lines (31 loc) · 1.11 KB
/
17. Radix Sort.js
File metadata and controls
36 lines (31 loc) · 1.11 KB
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
34
35
36
// RADIX SORT
// Escolhe um elemento pivô e joga a esquerda todos os números menores e a direita todos os números maiores e retorna o índice do elemento pivô, repetindo esse processo com todos os elementos, tanto na direita quanto na esquerda.
// Time: O(log n) for all cases
// Space: O(n)
function getDigit(num, i) {
return Math.floor(Math.abs(num) / Math.pow(10, i)) % 10;
}
function digitCount(num) {
if (num === 0) return 1;
return Math.floor(Math.log10(Math.abs(num))) + 1;
}
function mostDigits(nums) {
let maxDigits = 0;
for (let i = 0; i < nums.length; i++) {
maxDigits = Math.max(maxDigits, digitCount(nums[i]));
}
return maxDigits;
}
function 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;
}
radixSort([23, 345, 5467, 12, 2345, 9852])