桶排序(也被称为箱排序)也是分布式排序算法,它将元素分为不同的桶(较小的数组), 再使用一个简单的排序算法,例如插入排序(用来排序小数组的不错的算法),来对每个桶进行 排序。然后,它将所有的桶合并为结果数组。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| function insertSort(arr) { const { length } = arr; let temp; for (let i = 1; i < length; i++) { temp = arr[i]; let j = i; while (j > 0 && arr[j - 1] > temp) { arr[j] = arr[j - 1]; j--; }
arr[j] = temp; }
console.log(arr); }
function bucketSort(array, bucketSize = 3) { if (array.length < 2) { return array; } const buckets = createBuckets(array, bucketSize); return sortBuckets(buckets); }
function createBuckets(array, bucketSize) { let minValue = array[0]; let maxValue = array[0]; for (let i = 1; i < array.length; i++) { if (array[i] < minValue) { minValue = array[i]; } else if (array[i] > maxValue) { maxValue = array[i]; } } const bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1; const buckets = []; for (let i = 0; i < bucketCount; i++) { buckets[i] = []; } for (let i = 0; i < array.length; i++) { const bucketIndex = Math.floor((array[i] - minValue) / bucketSize); buckets[bucketIndex].push(array[i]); } return buckets; }
function sortBuckets(buckets) { const sortedArray = []; for (let i = 0; i < buckets.length; i++) { if (buckets[i] != null) { insertSort(buckets[i]); sortedArray.push(...buckets[i]); } } return sortedArray; }
const arr = [9, 3, 7, 4, 6];
console.log(insertSort(arr));
|