Counting Sort is a non-comparison-based sorting algorithm that sorts integers by counting the occurrences of each unique value in the array. It works best when the input elements are non-negative integers within a small range.
Unlike algorithms like Quick Sort or Merge Sort, Counting Sort does not use comparisons to sort elements. Instead, it relies on the idea that if you know how many elements are smaller than each value, you can place them directly into the correct position.
max + 1, where each index represents a value from the input.n is the number of elements and k is the range of input.public class CountingSortExample {
public static void countingSort(int[] arr) {
int n = arr.length;
// Find the maximum value in the array
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
// Create count array of size (max + 1)
int[] count = new int[max + 1];
// Store the frequency of each value
for (int i = 0; i < n; i++) {
count[arr[i]]++;
}
// Reconstruct the sorted array
int index = 0;
for (int i = 0; i < count.length; i++) {
while (count[i] > 0) {
arr[index++] = i;
count[i]--;
}
}
}
public static void printArray(int[] arr) {
for (int value : arr) {
System.out.print(value + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {4, 2, 2, 8, 3, 3, 1};
System.out.println("Original array:");
printArray(arr);
countingSort(arr);
System.out.println("Sorted array:");
printArray(arr);
}
}
Original array:
4 2 2 8 3 3 1
Sorted array:
1 2 2 3 3 4 8
Let’s sort the array:
[4, 2, 2, 8, 3, 3, 1]
Create a count array to track occurrences of each value from 0 to 8 (the max):
count[0] = 0
count[1] = 1
count[2] = 2
count[3] = 2
count[4] = 1
count[5–7] = 0
count[8] = 1
Count array:
[0, 1, 2, 2, 1, 0, 0, 0, 1]
Walk through the count array and for each value i, write it to the original array count[i] times:
1 → 1 time
2 → 2 times
3 → 2 times
4 → 1 time
8 → 1 time
Reconstructed sorted array:
[1, 2, 2, 3, 3, 4, 8]
[1, 2, 2, 3, 3, 4, 8]