Counting Sort, Stability, and Radix Passes

Derive the destination intervals of a stable counting sort and use stability to justify multi-digit ordering.

Source
Anbloq
Language
English
Created
Updated
Chapters
2
Reading time
1 min
In this article2 chapters
  1. A histogram determines output ranges
  2. A later digit pass preserves earlier refinements

A histogram determines output ranges

For keys in \(\{0,\ldots,K-1\}\), count occurrences \(c_j\) and compute start positions \(p_j=\sum_{i<j}c_i\). Key \(j\) occupies the consecutive slots beginning at \(p_j\) and ending immediately before \(p_j+c_j\). Traverse records in input order and advance that key’s slot pointer after each write. Equal keys retain their original relative order. This stable scatter costs \(O(n+K)\) work and uses buffers for the counts and output.

A later digit pass preserves earlier refinements

Sort \(d\) fixed-width digits in base \(K\) from least to most significant. After each stable pass, values are ordered by the digits processed so far. On \(29,11,21,13\), sorting by ones gives \(11,21,13,29\). Sorting stably by tens gives \(11,13,21,29\). Total work \(O(d(n+K))\) reflects the digit representation and cache footprint of the counts. This explains how digit access escapes the comparison lower bound. The word-RAM model spells out when a digit can be extracted in constant time.[1]

References

  1. MIT OpenCourseWare, Introduction to Algorithms: Lecture Notes ↩