function bucketSort (arr) {
var min = Math.min(...arr);
var max = Math.max(...arr);
var result = [];
var buckets = [];
// 桶的个数
var size = 3;
// 一个桶放几个元素,一个桶至少放一个
var num = Math.floor((max - min) / size) || 1;
for (let j = 0; j < arr.length; j++) {
const val = arr[j];
// 通过val计算桶偏移量
const cont = Math.floor((val - min) / size);
if (!buckets[cont]) {
buckets[cont] = [];
}
buckets[cont].push(val);
}
for (const bucket of buckets) {
console.log(bucket)
for (let i = 1; i < bucket.length; i++) {
var current = bucket[i];
var prevIndex = i - 1;
// 前面的比后面的大需要往后挪
while (prevIndex >= 0 && bucket[prevIndex]>current) {
bucket[prevIndex + 1] = bucket[prevIndex];
prevIndex--;
}
// 补上原来的位置
bucket[prevIndex + 1] = current;
}
console.log(bucket);
result = result.concat(bucket);
}
return result;
}
var a = bucketSort([3, 8, 6, 1, 5, 7, 9, 2, 4]);
console.log(a)
console