On this page
Counting Sort
Non-comparison sort for bounded integer keys.
Overview
Non-comparison sort for bounded integer keys.
Example
public static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++)
for (int j = 0; j < arr.length - 1 - i; j++)
if (arr[j] > arr[j + 1]) {
int tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp;
}
}
Common Use Cases
- Educational purposes
- Small datasets
- Nearly sorted data (insertion/bubble)
Pitfalls to Avoid
- O(n²) is too slow for large inputs
- Not stable unless implemented carefully
Related Topics
- Merge Sort
- Quick Sort
- Arrays.sort() internals
Best Practices
- Understand when to use counting sort versus simpler alternatives
- Write unit tests covering edge cases and failure paths
- Follow Java conventions and prefer standard library APIs when available
- Profile before optimizing — measure impact in your specific workload