Sorting the Mending Basket by Wear
My mending basket has four garments waiting for attention. I give each one a wear grade: 1 for a thin spot, 2 for a small hole and 3 for a tear that needs a patch. The grades arrive in basket order: 2 3 1 2. I want to arrange the work from least worn to most worn, so I can warm up my stitching on the smaller repairs.
Instead of comparing garments, I make three piles on paper and count how many belong in each. Then I read the counts back in grade order. This is counting sort, an approach to sorting integer keys from a known, limited range. Harold Seward developed the algorithm in the 1950s.
Here’s a GNU Smalltalk script that counts the grades and prints them in order:
| counts |
counts := Array new: 3 withAll: 0.
#(2 3 1 2) do: [:grade |
counts at: grade put: (counts at: grade) + 1
].
1 to: 3 do: [:grade |
(counts at: grade) timesRepeat: [
stdout nextPutAll: grade printString; nextPut: Character space
]
].
stdout nl.
Rust uses zero-based array positions, so grade 1 lives at position 0:
fn main() {
let mut counts = [0; 3];
for grade in [2, 3, 1, 2] {
counts[grade - 1] += 1;
}
for (index, count) in counts.iter().enumerate() {
for _ in 0..*count {
print!("{} ", index + 1);
}
}
println!();
}
Both print 1 2 2 3. For n grades and a range of k possible grades, the work takes O(n + k) time and O(k) extra space. That’s appealing when the range is small; a separate counter for every possible value would be wasteful if grades ran into the millions.
These examples sort only the grades. They don’t remember which sock or shirt supplied each one. A mending app that needs to keep garment details would need a fuller counting-sort implementation that places the records alongside their grades. For my basket, the counts are enough to see how the afternoon’s repairs are distributed.