Bucket sort distributes elements into buckets by value range, sorts each bucket (commonly with insertion sort), and concatenates the buckets. With uniformly distributed input each bucket is tiny, giving about O(n) average time. Worst case is O(n^2) when everything lands in one bucket.
Remember
bucket = value / 10; /* values 0..99 -> 10 buckets */
insert into bucket[bucket] keeping it sorted;
concatenate buckets 0..9;
Reference
Cheat Sheet
Keep these facts handy while you work with Bucket Sort in C.
Topic
Detail
Average
O(n) for uniform data
Worst
O(n^2)
Space
O(n + buckets)
Needs
Known value range
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Radix Sort.
Example 1 — Bucket two-digit numbers
Ten buckets, one per tens digit.
C
#include <stdio.h>
int main(void) {
int a[] = {78, 17, 39, 26, 72, 94, 21, 12, 23, 68};
int n = 10, b[10][10], cnt[10] = {0};
for (int i = 0; i < n; i++) {
int k = a[i] / 10;
int j = cnt[k]++;
while (j > 0 && b[k][j - 1] > a[i]) {
b[k][j] = b[k][j - 1];
j--;
}
b[k][j] = a[i];
}
int out[10], m = 0;
for (int k = 0; k < 10; k++) {
if (!cnt[k]) continue;
printf("bucket %d:", k);
for (int j = 0; j < cnt[k]; j++) {
printf(" %d", b[k][j]);
out[m++] = b[k][j];
}
printf("\n");
}
printf("sorted:");
for (int i = 0; i < m; i++) printf(" %d", out[i]);
printf("\n");
return 0;
}
Insertion into a bucket keeps it sorted as values arrive.
Concatenating buckets in order gives the sorted array.
Edge Cases & Pitfalls
Check these before relying on Bucket Sort in real programs.
skew
Skewed data
If most values share a bucket, bucket sort degrades to its inner sort.
size
Bucket capacity
This fixed 10x10 layout assumes at most 10 values per bucket; use lists for general data.
Remember
Key Takeaways
Distribute, sort, gather.
Works best on uniform data.
Inner sort handles each bucket.
One line: Bucket sort distributes elements into buckets by value range, sorts each bucket (commonly with insertion sort), and concatenates the buckets.
Frequently Asked Questions
A sorting algorithm that distributes values into ranges (buckets), sorts each bucket, and joins them.
When input is roughly uniformly distributed over a known range.
Continue with "C Radix Sort" next. Sort integers by each digit using stable counting sort passes. The C Sorting Algorithms hub lists every topic in order.