Bucket Sort
Example
const i = Math.floor(((x - min) / (max - min)) * k);
buckets[i].push(x);const range = max - min || 1;
const i = Math.min(k - 1, Math.floor(((x - min) / range) * k));
buckets[i].push(x);The maximum value maps to index k without clamping, and equal min and max divide by zero.
Common mistakes
- Putting the maximum value into bucket
kand gettingundefined.push. - Using bucket sort on skewed data, where most values fall into one bucket.
Key points
- The bucket index is clamped to
k - 1, so the maximum value does not land outside the array. - Code handles
max === minwithout dividing by zero. - Each bucket is sorted with a numeric comparator,
(a, b) => a - b.
Interview questions
What is the worst case of bucket sort?
When all values land in one bucket, it costs as much as the inner sort: O(n^2) with insertion sort.
Bucket sort vs counting sort: what is the difference?
Counting sort counts each exact integer value. Bucket sort groups ranges of values, so it also works for floats.
How many buckets should I use?
A common choice is about n buckets for n uniformly distributed values, which keeps each bucket small.
