CS255
Chris Pollett
Jan 31, 2017
Randomize-In-Place(A) 1. n := length[A] 2. for i :=1 to n 3. swap(A[i], A[Random(i,n)])
Lemma. Just prior to the ith iteration of the for loop, for each possible `(i-1)`-permutation, the subarray `A[1,i-1]` contains this permutation with probability `((n-i+1)!)/(n!)`
Proof. By induction on `i`.
Base case: When `i=1`, `A[1..0]` is the empty array. It is supposed to contain a given 0-permutation with probability `((n-1+1)!)/(n!) = (n!)/(n!)=1`. As a `0`-permutation has no elements and there is only one of them this is true.
Induction step: Assume just before the `i`th iteration, each `(i-1)`-permutation occurs in the `A[1..i-1]` with probability `((n-i+1)!)/(n!)`. A particular, `i`-permutation `langle x_1,...,x_(i-1), x_i rangle` consists of an `(i-1)`-permutation followed by `x_i`. By the induction hypothesis, the probability of the `i`-permutation is thus
`[((n-i+1)!)/(n!)] cdot Pr{A[i]= x_i| A[1..i-1] = langle x_1,...,x_(i-1) rangle}`.
The second factor is `1/(n-i+1)` since by line 3 of Randomize-in-Place, `x_i` is choosen at random from `A[i..n]`. So the probability of the `i`-permutation is
`((n-i+1)!)/(n!) cdot 1/(n-i+1) = ((n-i)!)/(n!)` as desired.
Theorem. Randomize-In-Place produces a uniformly chosen random permutation.
Proof. The program could generate any `n`-permutation. Further it terminates just before its `(n+1)`st iteration and thus by the lemma generates a given random `n`-permutation with probability:
`((n - (n+1) +1)!)/(n!) = (0!)/(n!) = 1/(n!)`
as desired.
What are the runtimes as a function of `n` (use O-notation) for Randomize-in-Place and Permute-By-Sorting?
Work out your answer. If you haven't already signed up for an account, sign up for an account on the discussion board (you need to create an account on https://www.yioop.com/, them add the discussion group).
Post your solutions to the Jan 31 In-Class Exercise Thread.
How many people must there be in a room before there is a `50%` chance that two were born on the same day of the year?
We can ask a variety of questions about the ball tossing process. As a first question, we ask:
How many balls fall in a given bin?
How many balls must one toss on average, until a given bin contains a ball?
How many balls must one toss on average, until every bin contains at least one ball?