The home where you level up

Save my spot

Bucket Sort

Term side of the Card.
Topic: Sorting Algorithms
Unit title: Bucket Sort
Categories: Algorithm
Explanation side of the Card

Explanation: The sorting algorithm that divides elements into buckets and sorts each bucket individually. Ideal for uniformly distributed data, achieving average O(n + k) complexity.

Example

Wrongjs
const i = Math.floor(((x - min) / (max - min)) * k);
buckets[i].push(x);
Rightjs
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 k and getting undefined.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 === min without 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.

The home where you level up

Daily 3-minute lessons to understand your AI's code.

No spam — just launch news.
Unsubscribe anytime. · Privacy Policy

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy