升序排列数组

  1. function bucketSort(arr) {
  2. const size = 5;
  3. const maxValue = Math.max(...arr);
  4. const minValue = Math.min(...arr);
  5. const diff = maxValue - minValue;
  6. const count = Math.floor(diff / size) + 1;
  7. const buckets = [];
  8. for (let i = 0; i < count; i++) {
  9. buckets[i] = [];
  10. }
  11. for (let j = 0; j < arr.length; j++) {
  12. const key = Math.floor((arr[j] - minValue) / size);
  13. buckets[key].push(arr[j]);
  14. }
  15. let idx = 0;
  16. for (let p = 0; p < buckets.length; p++) {
  17. buckets[p].sort((a, b) => a - b);
  18. while (buckets[p].length) {
  19. arr[idx] = buckets[p].shift();
  20. idx++;
  21. }
  22. }
  23. return arr;
  24. }

算法测试

  1. console.log(bucketSort([6, 11, 1, 8, 32, 5]));
  2. // [ 1, 5, 6, 8, 11, 32 ]
  3. console.log(bucketSort([4, 7, 2, 5, 3, -1, 9, 0]));
  4. // [ -1, 0, 2, 3, 4, 5, 7, 9 ]
  5. console.log(bucketSort([-12, -3, 0, 4, 3, 9]));
  6. // [ -12, -3, 0, 3, 4, 9 ]