Grades 6–8 · Computing
How can comparing and swapping pairs sort a list?
Sorting puts values into a chosen order while keeping the values themselves. A comparator examines two positions. In this demonstration it leaves the smaller value on the left and the larger on the right. When the pair is already ordered, it stays unchanged.
In the diagramCompare a pair; swap only if out of orderPair schedule: 1–2, then 2–3, then 1–2Start312After 1After 2After 33 comparisons · 2 swapsInput values are preserved while their order changes.
The fixed input is 3, 1, 2. The first comparison uses positions one and two. Because three is larger than one, they swap and the list becomes 1, 3, 2. The second comparison uses positions two and three; swapping three and two produces 1, 2, 3.
The last comparison returns to positions one and two. One is already smaller than two, so no swap occurs. There have now been three comparisons but only two swaps. A comparison is an observation and decision; a swap is a possible change resulting from that decision.
Throughout the trace, each list contains exactly the original values, only in different positions. This preserved collection is an invariant: a property that remains true while the algorithm runs. The ending list is increasing. The tiny schedule makes each operation visible without measuring real computer speed or establishing a universally efficient sorting method.
About this explanation
Starting knowledge: Compare integers, follow list positions and interpret a sequence of state changes.
Sources
- University of Canterbury, Computer Science Field Guide — Algorithms: Sorting