From 668f647371cd3ccd8c2e24114217b89a9149e43f Mon Sep 17 00:00:00 2001 From: Sharan Sukesh <77352136+sharansukesh1003@users.noreply.github.com> Date: Fri, 7 Oct 2022 12:26:19 +0530 Subject: [PATCH] Add files via upload --- Algorithms/radixSort.js.js | 47 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Algorithms/radixSort.js.js diff --git a/Algorithms/radixSort.js.js b/Algorithms/radixSort.js.js new file mode 100644 index 0000000..db0f318 --- /dev/null +++ b/Algorithms/radixSort.js.js @@ -0,0 +1,47 @@ +/* + * Radix sort is a non-comparative sorting algorithm. + * It avoids comparison by creating and distributing elements into buckets according o their radix. + * For elements with more than one significant digit, this bucketing process is repeated for each digit, + * while preserving the ordering of the prior step, until all digits have been considered. + * For this reason, radix sort has also been called bucket sort and digital sort. +*/ + +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; +} + +// example - radixSort([23,345,5467,12,2345,9852]) + + + + + + + +