Does this actually work?
Proof by induction.
Lemma: After iteration j (1 through n-1), keys 0 through j
are sorted.
Proof:
- Base case: When j=1, the single key data[0] is sorted.
- Inductive step: Assume after iteration j-1, keys 0 through j-1
are sorted.
- Note that we swap keys j and j-1 if they are out of order. We
then continue to move the smaller element down, until it is either
first or the item below it is smaller than it. By the inductive
hypothesis, the initial segment of the list is sorted. By the current
argument, the new item is in place, and by the inductive hypothesis,
the final segment of the list is sorted.
Next: Step 3: Efficiency
Up: INSERTION SORT
Previous: Explanation