Bucket Sort

Distributes elements into buckets, sorts each bucket individually (usually with insertion sort), then concatenates.

Best O(n+k) Avg O(n+k) Worst O(n²) Space O(n) Stable Yes In-place No Distribution

How it works

Distributes elements into buckets, sorts each bucket individually (usually with insertion sort), then concatenates.

Implementation

function bucketSort(arr) {
  const max = Math.max(...arr);
  const cnt = Math.floor(Math.sqrt(arr.length));
  const bk = Array.from({length: cnt}, () => []);
  for (const v of arr)
    bk[Math.min(cnt-1, Math.floor(v/(max+1)*cnt))].push(v);
  let idx = 0;
  for (const b of bk) {
    b.sort((a, c) => a - c);
    for (const v of b) arr[idx++] = v;
  }
}