3.6.6 · D3Sorting & Searching

Worked examples — Counting sort — O(n + k), integer keys only

2,606 words12 min readBack to topic

This page is a case gauntlet. The parent Counting Sort note taught you the three steps (Tally → Prefix sum → Place right-to-left). Here we make sure that no input can surprise you. We enumerate every kind of input counting sort can face, then work one full example per kind.


The scenario matrix

Every counting-sort input falls into one of these case classes (recall = item count, = max key). The examples below are labelled with the cell they cover.

# Case class What's special Example
C1 Plain non-negative ints the textbook happy path Ex 1
C2 All keys equal (degenerate) one bucket holds everything Ex 2
C3 Empty / single element and boundaries Ex 3
C4 Negative keys need a min-offset shift Ex 4
C5 Sparse range, many empty buckets — waste warning Ex 5
C6 Records + stability equal keys must keep order Ex 6
C7 Word problem (real world) modelling a real count Ex 7
C8 Exam twist — sort descending reverse without breaking stability Ex 8

Together C1–C8 touch every sign (positive, zero, negative), every degenerate shape (empty, singleton, all-equal), the limiting behaviour (), a real application, and a twist.

Before we start, picture the three arrays we keep manipulating. The figure below shows them for the very first example (): the lavender input keys, the mint count array (one cell per possible value ), and the butter output slots that get filled last.

Figure — Counting sort — O(n + k), integer keys only

Notice three separate arrays, three different lengths: input and output both have length , while count has length . The coral arrows show the two data flows we trace in every example — count (input → count) and place (count → output).


Worked examples

Ex 1 — C1: plain non-negative integers


Ex 2 — C2: all keys identical (degenerate)


Ex 3 — C3: empty and singleton (boundary , )


Ex 4 — C4: negative keys via min-offset


Ex 5 — C5: sparse range, (limiting behaviour)

The figure below makes the waste visible: three lonely coral bars (the occupied buckets ) surrounded by hundreds of near-empty lavender cells that the prefix-sum pass must nonetheless scan.

Figure — Counting sort — O(n + k), integer keys only

The huge empty gap between value 5 and value 1000 is the picture of "": the term is all width, no items.


Ex 6 — C6: records + stability


Ex 7 — C7: real-world word problem


Ex 8 — C8: exam twist — sort descending without breaking anything


Recall

Reminder for the questions below: = number of elements, = maximum key value (range ).

Recall Which scan direction keeps counting sort stable, and why?

Right-to-left over the input, decrementing count[v] before writing ::: The last equal element claims the highest free slot, so equal keys keep original order.

Recall How do you handle negative keys?

Offset by so keys map to , sort, then add back ::: Array indices start at 0 and can't be negative.

Recall When is counting sort a poor choice (Ex 5)?

When — the suffix/prefix-sum term dominates and the count array wastes memory ::: See the comparison bound; a sort wins.

Recall What is the tally array

also useful for in a word problem (Ex 7)? It is exactly the histogram of value frequencies ::: You get the frequency distribution for free before sorting.


See also: Prefix Sum / Cumulative Array · Bucket Sort · Time Complexity / Big-O