

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


The solutions in this homework are not complete. I only gave some directions to solve the problem. For algorithm problem, you must give the algorithm, analysis of correctness and time complexity.
Very similar to the algorithm given in class, and only modify the merge procedure given in the book.
(Divide and Conquer Algorithm)
Majority(k, S): Given k cards, if there are more than k/2 cards equivalent to one another, return true and give the card number.
If there is only one card available, return true and its number. If there are two cards available, return false if the two cards are different; return true and its number, otherwise.
(bool, num) Majority (n, S) // S is the set of numbers; return false or (true, value) 1: If(n =1) return true and its number; 2: If (n=2) return false if the two cards are different; return true and its number, otherwise. 3: Else{ //For simplicity, I consider the case that n is even. 4: Split the cards into two equal sets S1 ={1, 2, ….., n/2} S2 = {n/2+1, …, n}; (b1, value1) = Majority (n/2, S1); //b1,value1 are the return values from subproblem 1 (b2, value2) = Majority (n/2, S2); //b2,value2 are the return values from subproblem 2 5: If(b1 is false and b2 is false) Return false 6: Else if (b1 is false and b2 is true) { Compare value2 with all the cards in S to see if there are more than n/2 cards equivalent to it. If there are, return true and value2; else return false. } 7: Else if (b2 is false and b1 is true) { Compare value1 with all the cards in S to see if there are more than n/2 cards equivalent to it. If there are, return true and value1; else return false.} 8: Else if (b1 is true and b2 is true) { If (value1==value2) return true and value1; Else { Compare value1 with all the cards in S to see if there are more than n/2 cards equivalent to it. If there are, return true and value1; Else Compare value2 with all the cards in S to see if there are more than n/2 cards equivalent to it. If there are, return true and value1; else return false. } //end of Else } //end of if of line 3 } //end of the procedure
Time complexity: T(n) = 2T(n/2) +O(n). So, T(n) = O(nlogn).