Visualizers
Counting Sort Visualizer
Step-through animation of Counting Sort showing counts and output placement.
native (Canvas API)
Client-side
Input Array
Count Array (Indices 0-9)
Output Array
Ready to visualize
Execution Log
Current Action:
Idle
Phase Details:
1. Count occurrences of elements in Input.
2. Cumulative sum of counts to find output positions.
3. Build Output array backwards for stability.
Counting Sort Algorithm
Counting Sort is a non-comparison-based sorting algorithm. It works by counting the occurrences of each unique element in the input list, and using arithmetic to calculate their final positions in the sorted output array.
How It Works
- Find the maximum value in the input array. Create a count array of that size, filled with zeros.
- Iterate through the input array, incrementing the count array at the index corresponding to each input value.
- Perform a prefix sum (cumulative sum) on the count array. Each count value now stores the actual index range of the element in the sorted output.
- Iterate backwards through the input array, place each element into the output array using the count values as indices, and decrement the count value.
Implementation
function countingSort(arr) {
if (arr.length === 0) return arr;
const max = Math.max(...arr);
const min = Math.min(...arr);
const range = max - min + 1;
const count = Array(range).fill(0);
const output = Array(arr.length).fill(0);
for (let i = 0; i < arr.length; i++) {
count[arr[i] - min]++;
}
for (let i = 1; i < count.length; i++) {
count[i] += count[i - 1];
}
for (let i = arr.length - 1; i >= 0; i--) {
output[count[arr[i] - min] - 1] = arr[i];
count[arr[i] - min]--;
}
for (let i = 0; i < arr.length; i++) {
arr[i] = output[i];
}
return arr;
}