# a2sol - McGill University COMP251: Assignment 2 Solution...

This preview shows pages 1–3. Sign up to view the full content.

McGill University COMP251: Assignment 2 Solution Question 1 The partition procedure on a sorted array of length n always gives an empty subarray and an subarray of length n 1. So in this case the running time T ( n ) of Quicksort satisFes: T ( n ) = T ( n 1) + Θ( n ) So we have T ( n ) = T ( n 1) + Θ( n ) = T ( n 2) + Θ( n 1) + Θ( n ) = T ( n 3) + Θ( n 2) + Θ( n 1) + Θ( n ) . . . = T (1) + Θ(2) + Θ(3) + . . . + Θ( n 1) + Θ( n ) = Θ( n 2 ) As a result, T ( n ) = Ω( n 2 ). Question 2 (a) ±or an array A that is sorted in increasing order, the pairs ( i, j ) satisfying the given condition are (1 , 2) , (1 , 3) , . . . , (1 , n ) , (2 , 3) , (2 , 4) , . . . , (2 , n ) , . . . , ( n 1 , n ) The number of such pairs is ( n 1) + ( n 2) + . . . + 1 = ( n 1) n 2 (b) The idea for a divide-and-conquer algorithm is as follows. Given a subarray A [ ℓ . . . r ], we count the number of pairs ( i, j ) that satisfy the given condition (i.e., i < j and A [ i ] < A [ j ]) by dividing A [ ℓ . . . r ] into two halves A [ ℓ . . . m ] and A [( m + 1) . . . r ], and summing up the following numbers: 1. the number of such pairs where i < j m , and 2. the number of such pairs where m + 1 i < j r , and 3. the number of such pairs where i m and m + 1 j The Frst two quantities are computed recursively, and we are looking for a way to compute the last quantity in time O ( r ), so that the total running time will satisfy T ( n ) = 2 T ( n/ 2) + O ( n ) and the Master Theorem gives T ( n ) = O ( n ln n ). (Note that a brute-force way of computing the last quantity above–by comparing all number in the Frst half with all number in the second half–requires ( r - 2 ) 2 comparisons, so the running time would satisfy T ( n ) = 2 T ( n/ 2) + Θ( n 2 ) 1

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
and we would get T ( n ) = Θ( n 2 ), which is not good.) The number of pairs in (3) above can be computed without performing ( r - 2 ) 2 comparisons if the two halves
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 11/05/2009 for the course COMP COMP 251 taught by Professor Phuongnguyen during the Fall '09 term at McGill.

### Page1 / 6

a2sol - McGill University COMP251: Assignment 2 Solution...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online