|
| 1 | +/* |
| 2 | + * Radix sort is a non-comparative sorting algorithm. |
| 3 | + * It avoids comparison by creating and distributing elements into buckets according o their radix. |
| 4 | + * For elements with more than one significant digit, this bucketing process is repeated for each digit, |
| 5 | + * while preserving the ordering of the prior step, until all digits have been considered. |
| 6 | + * For this reason, radix sort has also been called bucket sort and digital sort. |
| 7 | +*/ |
| 8 | + |
| 9 | +function getDigit(num, i) { |
| 10 | + return Math.floor(Math.abs(num) / Math.pow(10, i)) % 10; |
| 11 | +} |
| 12 | + |
| 13 | +function digitCount(num) { |
| 14 | + if (num === 0) return 1; |
| 15 | + return Math.floor(Math.log10(Math.abs(num))) + 1; |
| 16 | +} |
| 17 | + |
| 18 | +function mostDigits(nums) { |
| 19 | + let maxDigits = 0; |
| 20 | + for (let i = 0; i < nums.length; i++) { |
| 21 | + maxDigits = Math.max(maxDigits, digitCount(nums[i])); |
| 22 | + } |
| 23 | + return maxDigits; |
| 24 | +} |
| 25 | + |
| 26 | +function radixSort(nums){ |
| 27 | + let maxDigitCount = mostDigits(nums); |
| 28 | + for(let k = 0; k < maxDigitCount; k++){ |
| 29 | + let digitBuckets = Array.from({length: 10}, () => []); |
| 30 | + for(let i = 0; i < nums.length; i++){ |
| 31 | + let digit = getDigit(nums[i],k); |
| 32 | + digitBuckets[digit].push(nums[i]); |
| 33 | + } |
| 34 | + nums = [].concat(...digitBuckets); |
| 35 | + } |
| 36 | + return nums; |
| 37 | +} |
| 38 | + |
| 39 | +// example - radixSort([23,345,5467,12,2345,9852]) |
| 40 | + |
| 41 | + |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | + |
0 commit comments