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: University of Waterloo CS 341 Algorithms Spring 2009 Solutions to Problem Set 1 1. [25 marks] Given an array of length n , containing n integers. A majority element is an integer that appears more than n/ 2 times in the array. (a) [5 marks] Develop an algorithm to find the majority, in O ( n log n ) time. Sort the array. Now if the array contains a majority element it must certainly be present at n/ 2 th position. Select the number at this position and check if it is indeed the majority element. (b) [10 marks] Develop an algorithm using only equality tests to find the majority in O ( n log n ) time. Let a [1 n ] be the given input array. The following is the pseudocode for computing the majority element of the elements between the i th and j th positions of the array. int majorityElement ( a [ i j ]) 1. if ( i == j ) return a [ i ]; 2. if ( i + 1 == j ) 3. if ( a [ i ] == a [ j ]) return a [ i ]; 4. else return NULL ; 5. else 6. m = ( i + j ) / 2 ; 7. l = majorityElement ( a [ i m ]); 8. r = majorityElement ( a [ m + 1 j ]); 9. if ( l negationslash = NULL ) 10. If l is the majority element in a [ i j ], return l ; 11. if ( r negationslash = NULL ) 12. If r is the majority element in a [ i j ], return r ; 13. return NULL ; Correctness Proof: We prove the correctness of the algorithm by induction on the array size. Clearly the algorithm is correct in the base case when there are 1 or 2 elements. Suppose there are n elements in the array. We observe that if an element e is the majority element of the array, then e must be a majority element in the first half of the array or in the second half of array. If e is the majority element of the first half of the array then (by induction on the array size) the recursive call on line 7 would return e and hence e would be detected as the majority element of the entire array. Similarly, if e is the majority element of the second half of the array then the recursive call on line 8 would return e and subsequently e would be detected as the majority element of the entire array. Also notice that if the majority element doesnt exist then we would always return NULL, irrespective of what the majority elements are in the recursive calls. This completes the correctness proof. 1 Running time: Let T ( n ) denotes the time complexity of the algorithm on n elements. It is clear from the algorithm that T ( n ) = 2 T ( n/ 2) + 2 n . But this recursion is similar to mergesort and has the complexity: T ( n ) = O ( n log n )....
View Full Document
- Spring '09