From a4390d0e0cbdcd94e2a75fab065eace4d3b496ae Mon Sep 17 00:00:00 2001 From: yigencong Date: Tue, 5 Mar 2024 18:27:19 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0lsd=E7=9A=84=E5=9F=BA?= =?UTF-8?q?=E6=95=B0=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sort/radixSort.mjs | 43 +++++++++++++++++++++++++++++++++++++++++++ sort/test.mjs | 4 +++- 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 sort/radixSort.mjs diff --git a/sort/radixSort.mjs b/sort/radixSort.mjs new file mode 100644 index 0000000..20683c6 --- /dev/null +++ b/sort/radixSort.mjs @@ -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; diff --git a/sort/test.mjs b/sort/test.mjs index 1526888..4692dba 100644 --- a/sort/test.mjs +++ b/sort/test.mjs @@ -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());