# Bucket Sort

> The Bucket Sort is an algorithm that sorts elements by distributing them into buckets, sorting each bucket individually.

## How does bucket sort work and when is it efficient?

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

- Topic: Sorting Algorithms
- Type: algorithm

## Example

Wrong:

```js
const i = Math.floor(((x - min) / (max - min)) * k);
buckets[i].push(x);
```

Right:

```js
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.

## Related cards

- [Counting Sort](https://wonderium.dev/algorithms/counting-sort.md)
- [Comparison Sort](https://wonderium.dev/algorithms/comparison-sort.md)
- [Hash Table](https://wonderium.dev/algorithms/hash-table.md)
- [O(n)](https://wonderium.dev/algorithms/o-n.md)
- [.sort()](https://wonderium.dev/js/array-sort.md)

---

- Level: [Algorithms](https://wonderium.dev/algorithms.md)
- HTML version: https://wonderium.dev/algorithms/bucket-sort
- Last updated: 2026-11-25
