Three Piles Before the Polish
Before a mud ball can become a dorodango, the soil needs some attention. Coarse bits belong in one pile, workable material in another, and fine dust can be saved for the surface. Imagine that a sieve has already classified each grain as 0, 1 or 2. How can we group those labels without making three new collections?
The Dutch national flag algorithm, associated with Edsger Dijkstra in the 1970s, uses three boundaries. The name comes from arranging three colours, but soil gives us a suitably dusty example. Both programs start with the same mixed collection and print the labels in the order 0 0 1 1 2 2, using their language’s array formatting.
| soil low mid high temp |
soil := #(2 0 1 2 0 1) copy.
low := 1. mid := 1. high := soil size.
[mid <= high] whileTrue: [
(soil at: mid) = 0
ifTrue: [temp := soil at: low. soil at: low put: (soil at: mid).
soil at: mid put: temp. low := low + 1. mid := mid + 1]
ifFalse: [(soil at: mid) = 2
ifTrue: [temp := soil at: high. soil at: high put: (soil at: mid).
soil at: mid put: temp. high := high - 1]
ifFalse: [mid := mid + 1]]].
soil printNl.
Smalltalk arrays begin at one; Rust slices begin at zero. In both versions, the section before low contains zeroes, and the section between low and mid contains ones. Smalltalk keeps twos after high; Rust keeps them starting at high. Everything else still needs inspection.
fn main() {
let mut soil = [2, 0, 1, 2, 0, 1];
let (mut low, mut mid, mut high) = (0, 0, soil.len());
while mid < high {
match soil[mid] {
0 => { soil.swap(low, mid); low += 1; mid += 1; }
1 => mid += 1,
2 => { high -= 1; soil.swap(mid, high); }
_ => panic!("expected a soil class from 0 to 2"),
}
}
println!("{soil:?}");
}
Rust’s high marks the first position of the finished two-section, one past the unexamined material. When we swap a two to that end, we leave mid alone: the item arriving there hasn’t been examined yet.
The method takes linear time and uses constant extra space. Its swaps can change the relative order of items in the same class, so it isn’t the right choice when that order matters. And the labels are only a model: actual dorodango still requires a real sieve, a careful hand with water, and patience at the polishing cloth.