1. Count table
Create one counter for every integer from 0 through maxValue.
const counts = Array(maxValue + 1).fill(0)Typorithm · medium
Step 1 of 8 · intro card
Sorting Algorithms
Counting Sort counts integer frequencies, then rebuilds the array by walking values in order.
Counting Sort is not comparison-based; it uses values as indexes.
The counts array needs a known, limited value range from 0 through maxValue.
The first pass counts how often each value appears.
The second pass walks the counts array from low to high and emits each value the counted number of times.
It can run in O(n + k), where k is the value range size.
Works best for small integer ranges.
Use counts[value] to store frequency.
Walk the counts array in numeric order.
Runtime is O(n + k).
This simple version returns a new result array.
function countingSort(arr, maxValue) {
const counts = Array(maxValue + 1).fill(0);
for (const value of arr) {
counts[value]++;
}
const result = [];
for (let value = 0; value < counts.length; value++) {
while (counts[value] > 0) {
result.push(value);
counts[value]--;
}
}
return result;
}Connect each part of the code to the concept before you type.
Create one counter for every integer from 0 through maxValue.
const counts = Array(maxValue + 1).fill(0)Scan the input and count how often each value appears.
for (const value of arr)The value itself is used as an index into the counts array.
counts[value]++This version writes sorted values into a new result array.
const result = []Walking counts from low to high produces ascending order.
for (let value = 0; value < counts.length; value++)Repeated values are pushed once for each count.
while (counts[value] > 0)Push the current value into the sorted output.
result.push(value)Decrease the count after emitting one copy.
counts[value]--Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
Input[5,1,4,2,8]
This teaching version groups n value references by k distinct keys before reconstruction. It also stores the ordered output. The input array is not counted as extra space.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state