feat: 添加lsd的基数排序

This commit is contained in:
LouisFonda 2024-03-05 18:27:19 +08:00
parent e1a7b5440e
commit a4390d0e0c
2 changed files with 46 additions and 1 deletions

43
sort/radixSort.mjs Normal file
View File

@ -0,0 +1,43 @@
import insertionSort from './insertion-sort.mjs';
/**
* 使用lsd基数排序
* @param {number[]} arr - 要基数排序的数组
*/
function radixSort(arr) {
let max = Math.abs(Math.max(...arr)); // 拿取数组中最大的数,用于计算长度
let buckets = Array.from({ length: 10 }, () => []);
let curDit = 1; // 当前比较的是哪个数位 1表示个位
while (Math.floor(max)) {
for (let i = 0; i < arr.length; i++) {
buckets[getNumByGidit(arr[i], curDit)].push(arr[i]); // 根据数位的大小放入对应的数位桶中
}
// 对buckets中的每个桶的元素做好排序这里我们调用之前的插入排序
for (let i = 0; i < buckets.length; i++) {
insertionSort(buckets[i]);
}
// 个位比较完成之后比较十位,在此之前要把个位有序的数组给原数组,并且把桶子清空
arr = buckets.flat();
buckets = Array.from({ length: 10 }, () => []);
max /= 10; // 处理下一数位
curDit++;
}
return arr;
}
/**
* @description 获取某位的数字
* @param {number} num - 传入的数值
* @param {number} dit - 要获取的位数
*/
function getNumByGidit(num, dit) {
if (!num) return 0;
let res = 0;
while (dit--) {
res = num % 10;
num = (num - res) / 10;
}
return res;
}
export default radixSort;

View File

@ -11,8 +11,9 @@ import {
quickSort5,
} from './quick-sort.mjs';
import bucketSort from './bucket-sort.mjs';
import radixSort from './radixSort.mjs';
const arr = generateRandomArray(100);
const arr = generateRandomArray(10000);
measureTime(bubbleSort, arr.slice());
measureTime(insertionSort, arr.slice());
@ -24,3 +25,4 @@ measureTime(quickSort3, arr.slice()); // 前后指针分解数组
measureTime(quickSort4, arr.slice()); // 不使用递归处理
measureTime(quickSort5, arr.slice()); // 去除不必要代码
measureTime(bucketSort, arr.slice()); // 去除不必要代码
measureTime(radixSort, arr.slice());