Counting sort
Medium TimeO(n + k) SpaceO(k)
Given an array arr of whole numbers, zero or greater, return them in ascending order without comparing any two values against each other. Duplicates appear as many times as they occur. The values have to stay small enough that a counter can be held for every one from 0 up to the largest.
Examples
Example 1
- Input
- arr = [4, 2, 2, 8, 3, 3, 1]
- Output
- Seven values ascending, with both 2s and both 3s kept.
[1,2,2,3,3,4,8]
Example 2
- Input
- arr = [0, 5]
- Output
- Two values, but six counters: the four between 0 and 5 stay empty.
[0,5]
The Code
function countingSort(arr) {
const max = Math.max(...arr);
const counts = new Array(max + 1).fill(0);
for (const x of arr) counts[x]++;
const out = [];
for (let v = 0; v <= max; v++) {
for (let c = 0; c < counts[v]; c++) out.push(v);
}
return out;
}
countingSort([4, 2, 2, 8, 3, 3, 1]);Done
The first 13 calls, of 31. This one does not fit on a page.
More like this
All sorting examples (8) →- Merge sort Divide and conquer — split in half, sort, then merge.
- Quick sort Pick a pivot, partition around it, recurse on each side.
- Bubble sort Repeatedly swap adjacent out-of-order pairs until sorted.
- Insertion sort Grow a sorted prefix, inserting each new item into place.
- Selection sort Find the smallest remaining element and swap it into place.
- Heap sort Build a max-heap, then repeatedly move the root to the back.