feat: 添加桶排序
This commit is contained in:
parent
5e63701e3f
commit
e1a7b5440e
28
sort/bucket-sort.mjs
Normal file
28
sort/bucket-sort.mjs
Normal file
@ -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;
|
@ -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()); // 去除不必要代码
|
||||
|
Loading…
x
Reference in New Issue
Block a user