Starting radix sort algorithm
Original Array
Current State
function radixSort(arr) {
// Find the maximum number to know the number of digits
const max = Math.max(...arr);
// Do counting sort for every digit
// Instead of passing digit number, we pass exp
// exp is 10^i where i is the current digit number
for (let exp = 1; Math.floor(max / exp) > 0; exp *= 10) {
countingSortByDigit(arr, exp);
}
return arr;
}
function countingSortByDigit(arr, exp) {
const n = arr.length;
const output = new Array(n).fill(0);
const count = new Array(10).fill(0);
// Store count of occurrences in count[]
for (let i = 0; i < n; i++) {
count[Math.floor(arr[i] / exp) % 10]++;
}
// Change count[i] so that count[i] contains
// position of this digit in output[]
for (let i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
// Build the output array
for (let i = n - 1; i >= 0; i--) {
const digit = Math.floor(arr[i] / exp) % 10;
output[count[digit] - 1] = arr[i];
count[digit]--;
}
// Copy the output array to arr[]
for (let i = 0; i < n; i++) {
arr[i] = output[i];
}
}