Sorting by Counting Keys
Counting sort builds frequencies over a bounded range of integral keys and uses those counts to determine the sorted output positions.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace a tiny range
For keys 2, 0, 2, 1, the counts for 0, 1, and 2 are 1, 1, and 2. Emitting those repetitions yields 0, 1, 2, 2. Frequency maps describe equivalent count state.
Check which bound matters
Initializing a dense count array for keys from 0 through a million can dominate four input observations. Stable sorting of records also needs a placement rule. See radix and counting sort.[1]
Build an output from exact key multiplicities
Suppose keys are integers from zero through four and the input is [4, 1, 4, 0, 2, 1]. Make one count cell for each allowed key. The position of the missing key three remains zero, while counts for one and four become two. See dictionary frequency counts.
Key 0 1 2 3 4
Count 1 2 1 0 2
Running end positions: 1, 3, 4, 4, 6
Reconstructed keys: 0, 1, 1, 2, 4, 4
Include key range and record stability in your contract
A huge key range can make the count array inefficient. If input items carry attached data, cumulative positions can place full records, with a consistent scan direction to preserve ties. Test equal keys with different payloads.