Radix Sort
with just use array
function radixSort(arr) {
const max = Math.max(...arr);
let digit = 0;
while (10 ** digit <= max) {
sort(arr, digit);
digit++;
}
return arr;
}
function sort(arr, digit) {
const bucket = new Array(10);
for (let i = 0; i < arr.length; i++) {
const curr = Number.parseInt(arr[i] / (10 ** digit));
const mod = curr % 10;
if (bucket[mod] === undefined) bucket[mod] = [];
bucket[mod].push(arr[i]);
}
let idx = 0;
for (let i = 0; i < bucket.length; i++) {
const subArr = bucket[i] ?? [];
for (const curr of subArr) {
arr[idx] = curr;
idx++;
}
}
return arr;
}
// Do not edit the line below.
exports.radixSort = radixSort;
with index
Last updated