This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: CS 473 Homework 4 Solutions Spring 2010 1. Suppose we want to write an efficient function S HUFFLE ( n ) that returns a permutation of the set { 1,2,..., n } chosen uniformly at random. (a) Prove that the following algorithm is not correct. [Hint: Consider the case n = 3 .] S HUFFLE ( n ) : for i 1 to n [ i ] i for i 1 to n swap [ i ] [ R ANDOM ( n )] return [ 1.. n ] Solution: Heres the oneline proof: 3 3 / 3! = 27 / 6 = 9 / 2 is not an integer. Here are the output probabilities for each permutation when n = 3: Pr [ 1 2 3 ] = 4 / 27 Pr [ 1 3 2 ] = 5 / 27 Pr [ 2 1 3 ] = 5 / 27 Pr [ 2 3 1 ] = 5 / 27 Pr [ 3 1 2 ] = 4 / 27 Pr [ 3 2 1 ] = 4 / 27 More generally, there are exactly n n possible outcomes for this algorithm, because there are n possible return values for each of the n calls to R ANDOM. Each of these outcomes occurs with probability 1 / n n . If each permutation is equally likely, then exactly n n / n ! different outcomes lead to each permutation. But for any n 3, the number n n / n ! is not an integer n ! is divisible by n 1, but n n is notso we have a contradiction. Thus, for any n 3, some permutations must be more likely than others. Rubric: 2 points max; all or nothing. Considering the case n = 3 is enough. (b) Consider the following implementation of S HUFFLE . S HUFFLE ( n ) : for i 1 to n [ i ] NULL for i 1 to n j R ANDOM ( n ) while ( [ j ] != NULL) j R ANDOM ( n ) [ j ] i return [ 1.. n ] Prove that this algorithm is correct. What is its expected running time? Solution: The algorithm is vacuously correct when n = 0, so assume n 1. The algorithm places the integer 1 uniformly at random into the array , say into slot [ j ] . By the induction hypothesis, the remainder of the algorithm fills the other n 1 slots of with a permutation of the set { 2,3,..., n } chosen uniformly at random. Thus, the output array is equally likely to be any permutation of the set { 1,2,..., n } . Let X i denote the number of calls to R ANDOM during the i th iteration of the outer loop; the running time of the algorithm is clearly ( i X i ) . During the i th iteration of the outer loop, exactly i 1 of the slots in the output array are already occupied. Thus, with probability ( i 1 ) / n , the while loop iterates more than once. Since the random numbers produced by R ANDOM are identically distributed, we have a recurrence E [ X i ] = 1 + i 1 n E [ X i ] , 1 CS 473 Homework 4 Solutions Spring 2010 whose solution is E [ X i ] = n / ( n i + 1 ) . Thus, the total expected number of calls to R ANDOM is exactly n X i = 1 n n i + 1 = n n X j = 1 1 j = n H n , which implies that the algorithms expected running time is ( n H n ) = ( n log n ) ....
View
Full
Document
 Spring '08
 Chekuri,C

Click to edit the document details