Sorting Spores at the Slide
A good lichen slide rewards patience. A thin section, a drop of water and a carefully lowered coverslip can reveal structures that were invisible in the field. At the microscope, I sketch what I see and mark each drawing according to whether the chosen feature is visible.
Back at the desk, suppose those marks are stored as zeroes and ones. I want the drawings without the feature first, followed by those with it. Two-pointer partitioning does that in place: one pointer looks for a misplaced one from the left, while another looks for a misplaced zero from the right. When both find one, they swap. When they meet or cross, the job is done.
Ruby makes the exchange read rather like a note to myself:
marks = [1, 0, 1, 0, 0, 1]
left, right = 0, marks.length - 1
while left < right
left += 1 while left < right && marks[left] == 0
right -= 1 while left < right && marks[right] == 1
marks[left], marks[right] = marks[right], marks[left] if left < right
end
puts marks.join(' ')
The result is 0 0 0 1 1 1. The C version follows the same paths through the array, with an explicit temporary value for the swap:
#include <stdio.h>
int main(void) {
int marks[] = {1, 0, 1, 0, 0, 1};
int left = 0, right = 5;
while (left < right) {
while (left < right && marks[left] == 0) left++;
while (left < right && marks[right] == 1) right--;
if (left < right) {
int temp = marks[left]; marks[left] = marks[right]; marks[right] = temp;
}
}
for (int i = 0; i < 6; i++) printf("%d%c", marks[i], i == 5 ? '\n' : ' ');
}
Each pointer only moves inward, so the work grows linearly with the number of marks and needs constant extra space. This is a small relative of the partitioning step used by quicksort, introduced in the early 1960s.
There is a cost to those convenient swaps: drawings within each group may change order. If field collection order matters, keep that information with each record and choose a stable grouping method instead. The marks here are deliberately simple; an actual observation also needs its specimen, location and preparation notes.