From e1a7b5440ef0a48166251be129614ef89c0d703e Mon Sep 17 00:00:00 2001 From: yigencong Date: Sun, 3 Mar 2024 23:49:58 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E6=A1=B6=E6=8E=92?= =?UTF-8?q?=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sort/bucket-sort.mjs | 28 ++++++++++++++++++++++++++++ sort/test.mjs | 11 ++++++++--- 2 files changed, 36 insertions(+), 3 deletions(-) create mode 100644 sort/bucket-sort.mjs diff --git a/sort/bucket-sort.mjs b/sort/bucket-sort.mjs new file mode 100644 index 0000000..0615787 --- /dev/null +++ b/sort/bucket-sort.mjs @@ -0,0 +1,28 @@ +function bucketSort(arr, bucketSize = 5) { + const maxVal = Math.max(...arr); + const minVal = Math.min(...arr); + + const bucketCount = Math.floor((maxVal - minVal) / bucketSize) + 1; // 通过最大值和最小值计算桶子的个数 + const buckets = new Array(bucketCount).fill().map(() => []); + + // 将元素放入桶中 + for (let i = 0; i < arr.length; i++) { + const bucketIndex = Math.floor((arr[i] - minVal) / bucketSize); // 通过当前桶判断该值应该放在哪个桶里面 + buckets[bucketIndex].push(arr[i]); + } + + // 在每个桶内部进行排序 + for (let i = 0; i < buckets.length; i++) { + buckets[i].sort((a, b) => a - b); // 此处可以使用对小数组排序快的数组,优先选择插入排序 + } + + // 合并所有桶的元素 + let result = []; + for (let i = 0; i < buckets.length; i++) { // 遍历所有的桶,把每个桶里面的数据放到新数组 + result = result.concat(buckets[i]); + } + + return result; +} + +export default bucketSort; diff --git a/sort/test.mjs b/sort/test.mjs index 0a44139..1526888 100644 --- a/sort/test.mjs +++ b/sort/test.mjs @@ -1,14 +1,18 @@ -import { generateRandomArray, measureTime } from '../util/index.mjs'; +import { generateRandomArray, isSort, measureTime } from '../util/index.mjs'; import { shellSort } from './shell-sort.mjs'; import insertionSort from './insertion-sort.mjs'; import { bubbleSort } from './bubble-sort.mjs'; import { mergeSort } from './merge-sort.mjs'; import { - quickSort, quickSort2, quickSort3, quickSort4, quickSort5, + quickSort, + quickSort2, + quickSort3, + quickSort4, + quickSort5, } from './quick-sort.mjs'; +import bucketSort from './bucket-sort.mjs'; const arr = generateRandomArray(100); -console.log(arr); measureTime(bubbleSort, arr.slice()); measureTime(insertionSort, arr.slice()); @@ -19,3 +23,4 @@ measureTime(quickSort2, arr.slice()); // 挖坑法分解数组 measureTime(quickSort3, arr.slice()); // 前后指针分解数组 measureTime(quickSort4, arr.slice()); // 不使用递归处理 measureTime(quickSort5, arr.slice()); // 去除不必要代码 +measureTime(bucketSort, arr.slice()); // 去除不必要代码