SMALLTALK LAB
Counting sort: trade comparisons for counts
Sort bounded integer data by building a frequency table, reconstructing the sequence, and checking its invariants in native Squeak.
Before you begin
You should be comfortable with Arrays, blocks and do:. The goal is a sorter for small nonnegative integer keys, not a replacement for every comparison sort.
These are native Squeak 6.1 examples. Each checkpoint is independent: open the download as text, copy one complete expression into Workspace and choose Print it. Do not file in the checkpoint collection as a class definition.
01 - Map keys to one-based slots
Squeak Arrays start at 1. A key of zero therefore belongs in slot 1; add one to every key before indexing. The limit is inclusive, so allocate limit + 1 slots.
| limit counts |
limit := 4.
counts := Array new: limit + 1 withAll: 0.
countsExpected: {0. 0. 0. 0. 0.}

Try it: Change limit to 0: one slot remains, because zero is a valid key.
02 - Record one occurrence
Read the old count, add one, and write it back. Parentheses make the two uses of at: unambiguous. The count records frequency, not the input position.
| counts key |
counts := Array new: 5 withAll: 0.
key := 3.
counts at: key+1 put: (counts at: key+1)+1.
countsExpected: {0. 0. 0. 1. 0.}

Try it: Repeat the update: slot 4 becomes 2.
03 - Build the whole histogram
Visit every input value once. The table has two zeros, one one, no twos, two threes and one four. Its entries must add up to the input length.
| input counts |
input := #(3 0 4 3 1 0).
counts := Array new: 5 withAll: 0.
input do: [:v | counts at: v+1 put: (counts at: v+1)+1].
countsExpected: {2. 1. 0. 2. 1.}

Try it: Permute the input: the histogram stays the same.
04 - Reconstruct in ascending order
Scan keys from smallest to largest. Emit each key as many times as its counter says. A zero counter runs the block zero times, automatically skipping missing keys.
| counts output |
counts := #(2 1 0 2 1).
output := OrderedCollection new.
0 to: 4 do: [:v |
(counts at: v+1) timesRepeat: [output add: v]].
output asArrayExpected: {0. 0. 1. 3. 3. 4.}

Try it: Change the last counter to 0: no four is emitted.
05 - Package the contract in a block
Validate the key range before any indexing. The block creates fresh storage and returns an Array. Keeping the inclusive limit explicit makes its memory cost visible at the call site.
| sort |
sort := [:input :limit | | counts output |
(limit isInteger and: [limit >= 0])
ifFalse: [Error signal: 'Use a nonnegative integer limit'].
(input allSatisfy: [:v | v isInteger and: [v between: 0 and: limit]])
ifFalse: [Error signal: 'Values must be integers in range'].
counts := Array new: limit + 1 withAll: 0.
input do: [:v | counts at: v+1 put: (counts at: v+1)+1].
output := OrderedCollection new.
0 to: limit do: [:v |
(counts at: v+1) timesRepeat: [output add: v]].
output asArray].
sort value: #(3 0 4 3 1 0) value: 4Expected: {0. 0. 1. 3. 3. 4.}

Try it: Try limit 3 with a 4 in the data. The guard rejects it before indexing.
06 - Check empty and repeated data
An empty input still produces an empty result. All-equal data keeps its multiplicity. These cases expose accidental assumptions that every key must occur.
| sort |
sort := [:input :limit | | counts output |
(limit isInteger and: [limit >= 0])
ifFalse: [Error signal: 'Use a nonnegative integer limit'].
(input allSatisfy: [:v | v isInteger and: [v between: 0 and: limit]])
ifFalse: [Error signal: 'Values must be integers in range'].
counts := Array new: limit + 1 withAll: 0.
input do: [:v | counts at: v+1 put: (counts at: v+1)+1].
output := OrderedCollection new.
0 to: limit do: [:v |
(counts at: v+1) timesRepeat: [output add: v]].
output asArray].
{sort value: #() value: 0.
sort value: #(2 2 2) value: 2}Expected: {#(). #(2 2 2)}

Try it: Check #(0) with limit 0; the answer is #(0).
07 - Verify order and retained multiplicities
For this deterministic family of inputs, compare with Squeak's trusted sorted collection. Equality checks both ordering and every repeated value. The source is not modified by either call.
| sort |
sort := [:input :limit | | counts output |
(limit isInteger and: [limit >= 0])
ifFalse: [Error signal: 'Use a nonnegative integer limit'].
(input allSatisfy: [:v | v isInteger and: [v between: 0 and: limit]])
ifFalse: [Error signal: 'Values must be integers in range'].
counts := Array new: limit + 1 withAll: 0.
input do: [:v | counts at: v+1 put: (counts at: v+1)+1].
output := OrderedCollection new.
0 to: limit do: [:v |
(counts at: v+1) timesRepeat: [output add: v]].
output asArray].
(0 to: 30) allSatisfy: [:n | | input |
input := (1 to: n) collect: [:i | (i*7) \\ 5].
(sort value: input value: 4) = input asSortedCollection asArray]Expected: true

Try it: Replace 7 with 3 in the generator and rerun.
08 - Reject an invalid key deliberately
Catch Error here only to test the guard. In a real application, validate or report the problem to the caller rather than silently replacing an invalid result.
| sort |
sort := [:input :limit | | counts output |
(limit isInteger and: [limit >= 0])
ifFalse: [Error signal: 'Use a nonnegative integer limit'].
(input allSatisfy: [:v | v isInteger and: [v between: 0 and: limit]])
ifFalse: [Error signal: 'Values must be integers in range'].
counts := Array new: limit + 1 withAll: 0.
input do: [:v | counts at: v+1 put: (counts at: v+1)+1].
output := OrderedCollection new.
0 to: limit do: [:v |
(counts at: v+1) timesRepeat: [output add: v]].
output asArray].
[sort value: #(0 -1 2) value: 2. false]
on: Error do: [:error | error messageText = 'Values must be integers in range']Expected: true

Try it: Test a fractional key such as 1/2; it must also be rejected.
Watch the computed states

Download the visual experiment. Select the entire expression and Do it. Change stage := 0. to another supported stage, close the previous window, and run again. The GIF replays those native states. This example needs native Squeak; no new browser playground compatibility is claimed.
Reason about correctness and limits
The work is O(n + k) for n values and k = limit + 1 possible keys. The count table costs O(k), and this version also allocates O(n) output. A huge sparse range can cost far more than sorting the few values directly.
This reconstructing version sorts values only. It does not preserve associated record identities and therefore makes no stability claim for records with equal keys. Stable counting sort needs positions and a separate output placement pass.
Negative keys need an offset based on the minimum key. Do not just take abs: that merges different values. Guard a practical maximum range before accepting untrusted data.
Three practice challenges
Challenge 1
Support keys from -2 through 2. What slot holds -2?
Show solution
Use slot = key - minimum + 1. With minimum -2, key -2 maps to 1; allocate maximum - minimum + 1 counters.
Challenge 2
Can this sorter handle ten billion possible keys efficiently?
Show solution
Not with a dense table. Prefer a comparison sort or count distinct keys in a Dictionary and sort those keys.
Challenge 3
What invariant should hold after the counting pass?
Show solution
The sum of counters equals the input size, and counter v+1 equals the number of occurrences of v.
Continue learning
Collections | Sorting Visualiser | Prefix Sums
Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Windows.