Finding loop invariants: why loops are correct

ClassNotes+

Finding the invariants

Karl Winklmann


Finding the invariant that lets you prove (partial) correctness of a loop amounts to understanding why the loop works.

Selection Sort

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.



Source Code


So what is the invariant in Selection Sort?

The same question comes up with other sorting algorithms, e.g., Bubble Sort and Insertion Sort.

ClassNotes+ Home Page
Email: ClassNotes+@cs.colorado.edu

Last edited (or copied to this place) at 12:17, Friday, April 26, 1996..