~/ learn/ comp-372/ cards/ Sorting in linear time
1 of 6

Type COUNTING-SORT (CLRS, 1-indexed; reverse placement for stability)

Type COUNTING-SORT (CLRS, 1-indexed; reverse placement for stability)

Answer

COUNTING-SORT(A, n, k) let B[1..n], C[0..k] be new arrays for i = 0 to k: C[i] = 0 for j = 1 to n: C[A[j]] = C[A[j]] + 1 for i = 1 to k: C[i] = C[i] + C[i-1] for j = n downto 1 B[C[A[j]]] = A[j] C[A[j]] = C[A[j]] - 1 return B

Count, then prefix-sum so C[i] is the position of the last value-i element, then place right-to-left (downto) — the reverse pass is what makes counting sort stable.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/7fcd80fc-f820-47ce-85a1-c27b9665f9a2/flashcard utf-8 LF