Finding loop invariants: why loops are correct |
![]() |
Why does Selection Sort work? The loop (well, the outer one) could be written as
i = 0;
while ( i != n-1 )
{
swap (i, position_of_largest_value_at_or_above (i) );
i++;
}
(Ah, those meaningful function names!)
Here is one way to explore this question. Change the data after or before any pass through the loop body. If our thinking is right then the algorithm will survive (i.e., continue to produce a sorted array) as long as you don't wipe out the loop invariant.
![]() |
You can interfere at any time, changing a data value by grabbing it with the mouse and stretching it or by dragging it to another place in the array. | ![]() |
ClassNotes+ Home Page