Bucket sort
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Bucket sort drops items into labelled buckets by range, sorts each small bucket, and then reads the buckets in order. It works best when values are spread fairly evenly, such as ratings, temperatures or percentages.
Practical use cases
- Web app: Rating histogram on a product page. A product page shows how many reviews gave 1 to 5 stars and lists reviews grouped by score. Dropping each review into its bucket is quick, and each bucket is tidied separately. The page builds in one pass even for lakhs of reviews.
- Web app: Grouping orders by price range. A catalogue lets shoppers browse by bands: under 500, 500 to 1,000, and so on. Dropping products into price buckets and sorting just inside each one is faster than sorting the whole catalogue, and it matches how the page is displayed.
- System: Sensor readings and distributed sorting. Temperature readings between 0 and 100 can be dropped into ten buckets and sorted bucket by bucket. Big-data systems do the same across machines, giving each machine one range of values to sort, and the pieces are simply joined at the end.
The story: Ten Piles of Answer Sheets
After the half-yearly exam, Mrs. Sharma carried a heavy bundle of answer sheets to the staff room. She wanted them ranked by marks, but sorting the whole bundle at once looked exhausting.
Grandpa Bhaskar, a retired teacher, had a trick. "Make piles on the table first: one pile for marks 0 to 9, one for 10 to 19, and so on. Go through the bundle once and drop each sheet in the right pile. No sorting yet, just throwing."
When the bundle was empty, each pile held just a few sheets. Sorting a small pile took a moment. Then Mrs. Sharma stacked the piles from the lowest range to the highest, and the whole class was ranked. The piles already do most of the work, because every sheet in a higher pile is bigger than every sheet in a lower pile.
This is bucket sort. It works beautifully when the values are spread out fairly evenly. If everybody scored between 40 and 49, all sheets land in one pile, and you are back to sorting the entire bundle.
How to spot this problem, and where you need it
You have many values spread over a known range and want to sort or group them quickly by dropping them into ranges first.
Signs you need it
- The values are decimals or numbers spread fairly evenly over a known range, such as percentages, prices or temperatures.
- The user interface already groups data in ranges, such as histograms, price bands or age groups.
- You need to split a big sort across several workers or machines, one range each.
Where to use it in a project
- Histograms, rating breakdowns and price-band filters on listing pages.
- Distributed or batch jobs that split data by range so each worker sorts one small piece.
The solution
Decide how many buckets you want and what range each covers. Go through the data once and drop each item into its bucket by simple arithmetic. Sort each bucket on its own, which is small, using a simple sort such as insertion sort. Finally join the buckets in order. If values are evenly spread, every bucket stays small and the total work is very low.
Payoff: Before: sorting 5 lakh prices as one huge list. After: ten small buckets sorted separately and joined, finishing much sooner.
Explain it like I am 8
Dump a mixed bag of numbers into labelled boxes: small numbers box, medium numbers box, big numbers box. Tidy up each box separately because it is small. Then line up the boxes one after another. Done.
How it works, step by step
- Decide the number of buckets and what range of values each bucket covers.
- Go through the list once, dropping each item into the bucket where it belongs.
- Sort each bucket on its own (the buckets are small, so insertion sort is fine).
- Join the buckets from the lowest range to the highest.
- Best when the data is spread evenly across the range.
The code in four languages
PHP
<?php
// Bucket sort for whole numbers: one bucket per range of $size values.
function insertionSort(array $a): array {
for ($i = 1; $i < count($a); $i++) {
$key = $a[$i];
$j = $i - 1;
while ($j >= 0 && $a[$j] > $key) { $a[$j + 1] = $a[$j]; $j--; }
$a[$j + 1] = $key;
}
return $a;
}
function bucketSort(array $a, int $size = 10): array {
if (!$a) return [];
$count = intdiv(max($a), $size) + 1; // how many buckets we need
$buckets = array_fill(0, $count, []);
foreach ($a as $v) {
$buckets[intdiv($v, $size)][] = $v; // drop into its range pile
}
$out = [];
foreach ($buckets as $b) {
foreach (insertionSort($b) as $v) $out[] = $v; // sort each pile, then join
}
return $out;
}
echo implode(', ', bucketSort([29, 25, 3, 49, 9, 37, 21, 43]));
// 3, 9, 21, 25, 29, 37, 43, 49JavaScript
// Bucket sort for whole numbers: one bucket per range of 'size' values.
function insertionSort(a) {
for (let i = 1; i < a.length; i++) {
const key = a[i];
let j = i - 1;
while (j >= 0 && a[j] > key) { a[j + 1] = a[j]; j--; }
a[j + 1] = key;
}
return a;
}
function bucketSort(a, size = 10) {
if (a.length === 0) return [];
const count = Math.floor(Math.max(...a) / size) + 1; // how many buckets we need
const buckets = Array.from({ length: count }, () => []);
for (const v of a) {
buckets[Math.floor(v / size)].push(v); // drop into its range pile
}
const out = [];
for (const b of buckets) {
out.push(...insertionSort(b)); // sort each pile, then join
}
return out;
}
console.log(bucketSort([29, 25, 3, 49, 9, 37, 21, 43]).join(', '));
// 3, 9, 21, 25, 29, 37, 43, 49Java
import java.util.*;
import java.util.stream.*;
public class Main {
// Bucket sort for whole numbers: one bucket per range of 'size' values.
static void insertionSort(List<Integer> a) {
for (int i = 1; i < a.size(); i++) {
int key = a.get(i);
int j = i - 1;
while (j >= 0 && a.get(j) > key) { a.set(j + 1, a.get(j)); j--; }
a.set(j + 1, key);
}
}
static List<Integer> bucketSort(int[] a, int size) {
List<Integer> out = new ArrayList<>();
if (a.length == 0) return out;
int count = Arrays.stream(a).max().getAsInt() / size + 1; // how many buckets we need
List<List<Integer>> buckets = new ArrayList<>();
for (int i = 0; i < count; i++) buckets.add(new ArrayList<>());
for (int v : a) {
buckets.get(v / size).add(v); // drop into its range pile
}
for (List<Integer> b : buckets) {
insertionSort(b); // sort each pile...
out.addAll(b); // ...then join
}
return out;
}
public static void main(String[] args) {
List<Integer> sorted = bucketSort(new int[]{29, 25, 3, 49, 9, 37, 21, 43}, 10);
System.out.println(sorted.stream().map(String::valueOf).collect(Collectors.joining(", ")));
// 3, 9, 21, 25, 29, 37, 43, 49
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
// Bucket sort for whole numbers: one bucket per range of size values.
func insertionSort(a []int) {
for i := 1; i < len(a); i++ {
key := a[i]
j := i - 1
for j >= 0 && a[j] > key {
a[j+1] = a[j]
j--
}
a[j+1] = key
}
}
func bucketSort(a []int, size int) []int {
if len(a) == 0 {
return []int{}
}
max := a[0]
for _, v := range a {
if v > max {
max = v
}
}
count := max/size + 1 // how many buckets we need
buckets := make([][]int, count)
for _, v := range a {
buckets[v/size] = append(buckets[v/size], v) // drop into its range pile
}
out := []int{}
for _, b := range buckets {
insertionSort(b) // sort each pile...
out = append(out, b...) // ...then join
}
return out
}
// join glues the numbers together with a separator, e.g. "1, 2, 3".
func join(a []int, sep string) string {
parts := make([]string, len(a))
for i, v := range a {
parts[i] = strconv.Itoa(v)
}
return strings.Join(parts, sep)
}
func main() {
fmt.Println(join(bucketSort([]int{29, 25, 3, 49, 9, 37, 21, 43}, 10), ", "))
// 3, 9, 21, 25, 29, 37, 43, 49
}Time: O(n + k) average, O(n²) worst · Extra space: O(n + k). With evenly spread data each pile is tiny. If everything lands in one pile, the in-pile sort does all the work.
Watch out for
- Picking bucket ranges that do not fit the data, so one bucket gets almost everything.
- Forgetting to sort inside each bucket. The piles are in order, but their contents are not.
- Using it for data with no known range, like arbitrary strings, without a good way to choose buckets.
Quick check
- What must you do after distributing items into buckets?
- Sort each bucket, then join them in order
- Reverse the buckets
- Throw empty buckets away and stop
- When is bucket sort slowest?
- When data is spread evenly
- When almost every item lands in the same bucket
- When there are many empty buckets
- Marks 0 to 49 with a bucket width of 10 gives how many buckets?
- Ten
- Fifty
- Five