Which distance measures improve in BUBBLESORT? If we can
find one that decreases steadily, then we can prove that BUBBLESORT is correct, since it will eventually work its way down to
zero (and therefore a sorted list).
Which measures decrease?
- unsortedp: That's what we're trying to find out!
- inversions: Yes! Each time a swap occurs, inversions decreases by
one.
Therefore,
total time, because we know there's at least one
swap per iteration of the ``while'' loop, and at most
inversions to start.
- adjacent inversions: Not really. Each swap fixes one adjacent
inversion, but might introduce 2 new ones:
- items out of place: Yes! After each execution of the entire
``for'' loop, the largest unsorted item moves into place. Therefore,
no more than n times through the while loop (or
time
all together).
- 2-3 8 1 7
- 2 3-8 1 7
- 2 3 1-8 7
- 2 3 1 7-8
- insertion index: Yes. Must decrease by at least one (but perhaps
more!).
Next: Step 3: Analyze Running
Up: BUBBLESORT
Previous: Measures of Sortedness