Bucket Sort
Algorithm · Stretch
Step through it: Sort First pattern
Step 1 of 4
Goal: does the list contain a duplicate? Checking every pair works but is slow. Idea: sort first, so equal numbers end up side by side.
Step 2 of 4
After sorting: 2, 2, 5, 7, 9. Equal numbers are now neighbours.
Step 3 of 4
Now one pass comparing each number with the next: 2 and 2 match. Duplicate found. Sorting often turns a hard search into a simple neighbour check, and makes tricks like two pointers and interval merging possible.
Step 4 of 4
Your turn.
Complexity
The computational complexity depends on the algorithm used to sort each bucket, the number of buckets to use, and whether the input is uniformly distributed.
The worst-case time complexity of bucket sort is
O(n^2) if the sorting algorithm used on the bucket is insertion sort, which is the most common use case since the expectation is that buckets will not have too many elements relative to the entire list. In the worst case, all elements are placed in one bucket, causing the running time to reduce to the worst-case complexity of insertion sort (all elements are in reverse order). If the worst-case running time of the intermediate sort used is O(n * log(n)), then the worst-case running time of bucket sort will also be
O(n * log(n)).
On average, when the distribution of elements across buckets is reasonably uniform, it can be shown that bucket sort runs on average O(n + k) for k buckets.
Bucket sort, or bin sort, is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm.
Algorithm
Bucket sort works as follows:
- Set up an array of initially empty
buckets. - Scatter: Go over the original array, putting each object in its
bucket. - Sort each non-empty
bucket. - Gather: Visit the
bucketsin order and put all elements back into the original array.
Elements are distributed among bins:

Then, elements are sorted within each bin:

Code
import RadixSort from '../radix-sort/RadixSort';
/**
* Bucket Sort
*
* @param {number[]} arr
* @param {number} bucketsNum
* @return {number[]}
*/
export default function BucketSort(arr, bucketsNum = 1) {
const buckets = new Array(bucketsNum).fill(null).map(() => []);
const minValue = Math.min(...arr);
const maxValue = Math.max(...arr);
const bucketSize = Math.ceil(Math.max(1, (maxValue - minValue) / bucketsNum));
// Place elements into buckets.
for (let i = 0; i < arr.length; i += 1) {
const currValue = arr[i];
const bucketIndex = Math.floor((currValue - minValue) / bucketSize);
// Edge case for max value.
if (bucketIndex === bucketsNum) {
buckets[bucketsNum - 1].push(currValue);
} else {
buckets[bucketIndex].push(currValue);
}
}
// Sort individual buckets.
for (let i = 0; i < buckets.length; i += 1) {
// Let's use the Radix Sorter here. This may give us
// the average O(n + k) time complexity to sort one bucket
// (where k is a number of digits in the longest number).
buckets[i] = new RadixSort().sort(buckets[i]);
}
// Merge sorted buckets into final output.
const sortedArr = [];
for (let i = 0; i < buckets.length; i += 1) {
sortedArr.push(...buckets[i]);
}
return sortedArr;
}References
Practice
Sort First
- Contains DuplicateEasy
- Valid AnagramEasy
- Meeting RoomsEasy
- Merge Sorted ArrayEasy
- Sort ColorsMedium
- Largest NumberMedium
- H-IndexMedium
- Wiggle Sort IIMedium
- Sort an ArrayMedium
- Custom Sort StringMedium
- Insertion Sort ListMedium
- Maximum GapHard
- Count of Smaller Numbers After SelfHard
Spotted a mistake or something unclear? Report it on GitHub.