基数排序 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/2/21 21:32:17
基数排序
基数排序是一种排序算法,它通过按具有相同有效位置和值的各个数字对键进行分组,对具有整数键的数据进行排序。
我们需要编写一个 JavaScript 函数,该函数以文字数组作为唯一参数。该函数应使用基数排序算法按升序或降序对数组进行排序。
示例
以下是代码 −
const arr = [45, 2, 56, 2, 5, 6, 34, 1, 56, 89, 33];
const radixSort = (arr = []) => {
const base = 10;
let divider = 1;
let maxVal = Number.NEGATIVE_INFINITY;
while (divider === 1 || divider <= maxVal) {
const buckets = [...Array(10)].map(() => []);
for (let val of arr) {
buckets[Math.floor((val / divider) % base)].push(val);
maxVal = val > maxVal ? val : maxVal;
}
arr = [].concat(...buckets);
divider *= base;
};
return arr;
};
console.log(radixSort(arr));
输出
以下是控制台上的输出 −
[ 1, 2, 2, 5, 6, 33, 34, 45, 56, 56, 89 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

