Proofs: Selection sort
These are the human proofs of Selection sort, at full length.
Selection sort sorts the array and keeps its items full
This proof shows: correctness.
Let be the input array of length . Items may repeat, so we treat each collection of items as a multiset.
Theorem. SELECTION-SORT stops, and at the end is a permutation of in non-decreasing order.
Proof. We use this invariant of the loop of line L1, before the step for :
(I) is a permutation of . The part is sorted. Each item of is at most each item of .
Start. For the part is empty, so the last two statements hold, and no item has moved.
The scan. Fix a step . For the loop of line L3 we use this invariant, before the step for :
(J) , and is at most each item of .
Line L2 sets , and the first step has . The part has the one item , so (J) holds. In the step for , if , line L5 sets . Then is less than the old least item, so it is at most each item of . Otherwise , and is still at most each item of . So (J) holds for . The loop runs for and stops with . Then is a least item of , and . Lines L2 to L5 do not write to .
Maintenance. Assume (I) before the step for , and let at the end of the scan. Line L6 swaps and , so is still a permutation of . Now . Each item of the old is at most , by (I), because was in . So is sorted. The new part holds the items of the old without one copy of . Each of these items is at least , by the scan, and at least each item of , by (I). So (I) holds for .
End. The loop of line L1 runs for , a finite range, so the algorithm stops. If , the loop does not run, and an array of at most one item is sorted. If , (I) holds for . Then is sorted, and each of its items is at most . So is sorted, and by (I) it is a permutation of .
Comparisons. The scan for makes one comparison for each from to , so comparisons. No other line compares items. The sum over is , on each input.