Data Structures and Algorithms • C# examples
Counting Sort, Radix Sort, and Bucket Sort
Use distribution-based sorting when key ranges or value distributions make comparison sorting wasteful.
Concept
Counting sort counts occurrences for a bounded integer key range. Radix sort orders digits over multiple stable passes. Bucket sort distributes values into ranges and sorts each bucket. These approaches can beat comparison sorting under specific assumptions, but their memory and runtime depend on key width, range, and distribution.
How to approach it
State the domain and range up front; use stable passes when later digit passes depend on earlier ordering.
Complexity
Counting O(n + k), radix O(d(n + k)), where k is digit range and d is digit count.
C# example
int[] counts = new int[maxValue + 1];
foreach (int value in values) counts[value]++;
int outputIndex = 0;
for (int value = 0; value < counts.Length; value++)
for (int count = 0; count < counts[value]; count++)
values[outputIndex++] = value;
Expected result or behavior
The values are rewritten in ascending order when all values are in [0, maxValue].
Practice exercise
Estimate when a large key range makes counting sort less attractive than comparison sorting.
Key takeaway: Non-comparison sorts gain speed by exploiting structure in the keys.