Proofs: Introsort
These are the human proofs of Introsort, at full length.
Introsort sorts every input, in O(n log n) time full
This proof shows: correctness, termination.
We use three facts proved on other pages. HEAPSORT ends and sorts , changing nothing else. INSERTION-SORT does the same. HOARE-PARTITION, for , ends and returns with , after permuting so that each item of is at most each item of ; see Hoare partition. Lines L11 to L15 are that procedure written with only: "until " is "until not ".
Lemma 1. For every range with and every , INTRO ends, changes only , permutes it, and leaves it sorted.
Proof. By strong induction on . Fix a call, and let be its first range. We claim that at the start of each pass of the loop of line L2:
(I) ; the items of are a permutation of the original ones; and are sorted; and each item of is at most each item of , and each item of is at most each item of .
At the first pass the two outer parts are empty, so (I) holds. Take a pass with and . Lines L5 and L6 only exchange two items of the range. The positions , and lie in the range, so does. Line L7 is called with , so it returns with , and each item of is at most each item of . Both parts and are non-empty and shorter than .
In line L8, the recursive call sorts the left part by the induction hypothesis and touches nothing else. The left part now is sorted, its items are at least the items of (they were in the range before), and at most the items of the right part, which were not moved. So setting keeps (I). Line L9 is the same with the roles of the parts swapped. Each pass makes smaller, so the loop ends.
The loop ends in one of two ways. If at line L3, HEAPSORT sorts . If , line L10 sorts it. Either way the middle part becomes sorted and keeps its set of items, so by (I) its items still lie between the two outer parts. Then is the sorted left part, then the sorted middle, then the sorted right part, with each part at most the next, which is a sorted sequence.
Theorem (correctness and termination). INTROSORT ends and leaves sorted.
Proof. If , the array is sorted and line L1 does nothing. Otherwise line L1 calls INTRO on the whole array, and Lemma 1 applies.
Theorem (time). INTROSORT makes comparisons and takes time.
Proof. Each call of INTRO receives a budget that is at most its caller's budget minus 1, and each pass of the loop lowers by 1 before it partitions. Call a partitioning step of depth one that runs with the budget after line L4. Then , so . The ranges partitioned at one depth are disjoint, because a step only works inside the range left to it by the step one depth less, and the ranges of the two parts are disjoint. HOARE-PARTITION and the median of three cost on items, so all the steps of one depth cost , and all depths cost . The ranges given to HEAPSORT are disjoint, and with sizes they cost . The ranges given to INSERTION-SORT are disjoint with , so they cost .