Bucket sort in C: solved exercise
Bucket sort in C: solved exercise
If you searched for a solved bucket sort exercise in C, here is the full implementation: it distributes elements into buckets, sorts each bucket with insertion sort, and concatenates them, achieving expected O(n) when data is uniformly distributed in [0, 1).
Bucket sort is one of the few sorting algorithms that breaks the Ī©(n log n) comparison-sort barrier, but only under the assumption of uniform distribution.
Problem statement
Sort the array {0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68} using bucket sort with 10 buckets. Show the bucket contents before sorting them and the final array.
C solution
Expected output
Common mistakes
- Not freeing bucket memory: each bucket is a linked list that must be freed with
freeto avoid memory leaks. - Not checking that
mallocreturnsNULL: allocation can fail on low-memory systems. - Computing the bucket index with
(int)(val * NB)without clamping: ifval == 1.0, the index would beNB, out of bounds. - Assuming bucket sort is always O(n): in the worst case (all elements in the same bucket) it degenerates to O(n²) with insertion sort as the inner algorithm.
Practical use
Bucket sort is used in rendering systems (distributing particles by depth), in histogram computation, and in the distribution phase of radix sort. It is especially efficient when data comes from a uniform distribution, such as randomly generated floating-point numbers in [0, 1).
Recommended next exercise
- Counting sort in C: solved exercise
- Radix sort in C: solved exercise
- Heap sort in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Why can bucket sort be O(n) if it uses an inner insertion loop?
Because when data is uniformly distributed, the expected number of elements per bucket is n/k (where k is the number of buckets). With k ā n, each bucket has on average 1 element, and insertion sort on each bucket is O(1). The total across all buckets is O(n) in the average case.
How many buckets should I use?
The general rule is to use as many buckets as elements (k = n), giving expected O(n). Fewer buckets increase the insertion time per bucket; too many buckets increase the overhead of managing empty buckets.
Can I use bucket sort with integers?
Yes, either by normalizing values to [0, 1) or by using the value directly as a bucket index (equivalent to counting sort for small ranges). For integers in [min, max], the bucket index is (val - min) * NB / (max - min + 1).