Proofs: Insertion sort
These are the human proofs of Insertion sort, at full length.
Insertion sort sorts the array and keeps its items full
This proof shows: correctness.
Let be the array at the start. We prove the invariant of the outer loop:
(I) Before the step for , the part is a permutation of in non-decreasing order, and .
Start. For , the part has one item, so it is sorted. No item has moved yet.
Step. Assume (I) before the step for . Line L2 sets . For the inner loop we use this invariant:
(J) . The part is not changed. The part is the old , moved one place right. Each item of is larger than .
Before the first test of line L4, and is empty, so (J) is true. If the test of line L4 is true, then . Line L5 copies to , and line L6 makes one less. So (J) is true again. The value becomes smaller in each step and , so the inner loop stops.
When the inner loop stops, or . Line L7 puts at . Now:
- each item of is at most , because the old part was sorted and , or the part is empty;
- ;
- each item of is larger than , by (J), and these items are in the old order.
So is sorted. It holds the old and , so it is a permutation of . The items after did not change. This is (I) for .
End. The loop stops with . By (I), is a permutation of in non-decreasing order.
Stability. An item moves right in line L5 only past an item that is larger than . So never moves before an item that is equal to it and that was before it in .