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()); // 去除不必要代码