Utilizes a helper function getDigit to retrieve a specific digit of a number based on its place value. This is crucial for placing each number in the appropriate "bucket" during the sorting process.
Digit Counting:
Another helper, digitCount, determines the number of digits in a number, which is vital for knowing how many passes the sorting algorithm needs to make over the data.
Identify Maximum Digits:
The function mostDigits scans through the array to find the number with the maximum number of digits, which dictates the number of sorting passes needed.
Sorting Logic:
For each digit place starting from the least significant digit, the algorithm distributes the elements into buckets (0-9 for decimal values) based on their digit value at the current position. After each pass, the elements are collected back from the buckets, preserving the new order.
1//Radix Sort is a linear sorting algorithm that sorts elements by processing them digit by digit.2// It is an efficient sorting algorithm for integers or strings with fixed-size keys. 3let arr = [121,432, 564, 23, 1, 45, 788]
45functiongetDigit(num, place) {
6returnMath.floor(Math.abs(num) / Math.pow(10, place)) % 10;
7}
89functiondigitCount(num) {
10if (num === 0) return1;
11returnMath.floor(Math.log10(Math.abs(num))) + 1;
12}
1314functionmostDigits(nums) {
15let maxDigits = 0;
16for (let i = 0; i < nums.length; i++) {
17 maxDigits = Math.max(maxDigits, digitCount(nums[i]));
18 }
19return maxDigits;
20}
2122functionradixSort(arr) {
23let maxDigitCount = mostDigits(arr);
24for (let k = 0; k < maxDigitCount; k++) {
25let digitBuckets = Array.from({length: 10}, () => []);
26for (let i = 0; i < arr.length; i++) {
27let digit = getDigit(arr[i], k);
28 digitBuckets[digit].push(arr[i]);
29 }
30 arr = [].concat(...digitBuckets);
31 }
32return arr;
33}
3435console.log(radixSort(arr));