Exercise 5.3-1

Professor Marceau objects to the loop invariant used in the proof of Lemma 5.5. He questions whether it is true prior to the first iteration. He reasons that we could just as easily declare that an empty subarray contains no 0-permutations. therefore, the probability that an empty subarray contains a 0-permutation should be 0, thus invalidating the loop invariant prior to the first iteration. Rewrite the procedure RANDOMIZE-IN-PLACE so that its associated loop invariant applies to a nonempty subarray prior to the first iteration, and modify the proof of Lemma 5.5 for your procedure.

REWRITTEN-RANDOMIZE-IN-PLACE(A):

1 swap A[1] with A[RANDOM(1, n)]

2 n = A.length

3 for i = 2 to n:

4      swap A[i] with A[RANDOM(i, n)]

This code is identical in runtime to the originato RANDOMIZE-IN-PLACE algorithm, but by moving the first iteration of the for loop outside the loop itself, it cleanly allows us to redefine the proof of Lemma 5.5 to start with \(i = 2\) rather than \(i = 1\). By doing this, our initial state no longer refers to an empty subarray and so we completely avoid needing to worry about 0-permutations at all.