forked from thuva4/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
53 lines (49 loc) · 1.36 KB
/
Copy pathindex.js
File metadata and controls
53 lines (49 loc) · 1.36 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* get the digit at the given place value
* @param {number} num number
* @param {number} place place
* @return {number} digit in the given place
*/
function getDigit(num, place) {
return Math.floor(Math.abs(num) / Math.pow(10, place)) % 10;
}
/**
* get the number of digits in a number
* @param {number} num number
* @return {number} count of digits
*/
function digitCount(num) {
if (num === 0) return 1;
return Math.floor(Math.log10(Math.abs(num))) + 1;
}
/**
* get the number of digits in the largest number
* @param {array} nums numbers
* @return {number} count of digits
*/
function mostDigits(nums) {
let maxDigits = 0;
for (let i = 0; i < nums.length; i++) {
maxDigits = Math.max(maxDigits, digitCount(nums[i]));
}
return maxDigits;
}
/**
* Sort array using radix sort
* @param {array} arrOfNums array of unsorted numbers
* @return {array} Sorted array.
*/
function radixSort(arrOfNums) {
const maxDigitCount = mostDigits(arrOfNums);
for (let k = 0; k < maxDigitCount; k++) {
const digitBuckets = Array.from({length: 10}, () => []); // [[], [], [],...]
for (let i = 0; i < arrOfNums.length; i++) {
const digit = getDigit(arrOfNums[i], k);
digitBuckets[digit].push(arrOfNums[i]);
}
// New order after each loop
arrOfNums = [].concat(...digitBuckets);
}
return arrOfNums;
}
module.exports = radixSort;