130 likes | 316 Views
Finding the Majority Element. Section 5.7. Definition. An integer x in the array A[1..n] is the majority element iff x appears more than n/2 times in A, that is at least n/2 if n is odd n/2 + 1 = n/2 + 1 if n is even. Theorem.
E N D
Finding the Majority Element Section 5.7
Definition • An integer x in the array A[1..n] is the majority element iff x appears more than n/2 times in A, that is at least n/2 if n is odd n/2 + 1 = n/2 + 1 if n is even
Theorem • The majority element is unique! Sorted A • Remark: if there is majority then it should be at A[n/2].
Problem • Given an array A[1..n], find the majority element of A (if it exists). • Remarks: the Majority element is the most frequent element but the opposite is not true.
Solution • Trivial solution is to compare all elements and keep counters for each element. This takes (n2). • Sort the array first and then count. This takes (n log n). • Find the median (the n/2-smallest element) which is the majority (if exists). Takes (n) but with big constant factor. • Use induction Technique.
Observations • If two different elements are removed from the array A then the majority of the old array remains as the majority of the new one. Because the worst is to remove one element from the majority. Largest frequency n/2 +1 -1 > (n-2)/2 • If the majority exists then it occurs in at least two consecutive positions or A[n] is the majority element. M D M D M D M D M D M D M D M D M D M D M D M D M D M D M D M D M D M D M D M D M M D M D M D M D M D M D M D M D M M D M D
Algorithm: Majority Input: A[1..n] Output: majority if exists, or none. c candidate(1) % finds a candidate only count 0 For j 1 to n if A[j]=c then count count +1 End for If count > n/2 then return c else return none
Procedure Candidate(m) j m; c A[m]; count 1 While( j<n and count >0) j j+1 if A[j]=c then count count +1 else count count -1 End While If j=n then return c else return candidiate(j+1)
Example • 323232323232323233232323232323 Count > 0, and there is a majority • 12345677 Count > 0 but has no majority
Analysis • The majority algorithm takes at most 2n comparisons • Worst case: 11111111111111111111111111111111 • Best Case: 12121212121212121212121212121212