Proofs: Hire-assistant
These are the human proofs of Hire-assistant, at full length.
Hire-assistant hires exactly the candidates who beat all earlier ones full
This proof shows: correctness.
We use the pseudocode of the page, with candidates and a dummy candidate that is worse than each real candidate. A position is a record if is better than each of . Since is worse than all, position 1 is always a record.
Claim. HIRE-ASSISTANT hires exactly the records, in increasing order of position, and at the end is a best candidate of when .
Proof. We use this invariant of the loop of line L2.
(I) Before the iteration for , with : (a) , and is at least as good as each of ; (b) the hires so far are exactly the records , in increasing order.
Initialization. Before the first iteration, and line L1 sets . Part (a) holds because is the dummy alone. Part (b) holds because no hire was made and no record exists.
Maintenance. Assume (I) for . By (a), is a maximum of . So is better than if and only if is better than each of , that is, if and only if is a record. Line L3 does not change or the hires.
- If is a record, line L4 is true. Line L5 sets , and is better than each of , so (a) holds for . Line L6 hires , which is larger than each earlier hire, so (b) holds for .
- If is not a record, line L4 is false and nothing changes. is not better than , so in a total order is at least as good as , and (a) holds for . No record was missed, so (b) holds for .
Termination. The loop stops with . By (b), the hires are exactly the records , in order. By (a), is at least as good as each of . If , position 1 is a record, so a real candidate was hired and ; hence is a best candidate of , and is the last hire.
Cost. The loop runs times and each iteration does one comparison in line L4 and other work, so the time is . The number of hires is the number of records.
Expected number of hires. Let the order of be a uniform random permutation of distinct candidates, and let be the indicator that is a record. The relative order of is uniform on the orders, so each of these positions holds the best of them with probability , and . By linearity of expectation, . For RANDOMIZED-HIRE-ASSISTANT, the shuffle makes the order uniform for each fixed input of distinct candidates, so the same computation gives for each input.