|
A[1..N] = 1 4 5 6 4 4 4 7 2 3 4 4 4 |
The majority element in the example is 4.
Q = ∅ // Q is a list of the form <Value, Count> for ( i = 1; i <= N; i++ ) if ( A[i] ∈ Q ) { increase A[i]'s count by 1; } else { insert <A[i], 1> in Q; } for ( each e ∈ Q ) if ( e.count > N/2 ) print e; |
winner = A[1]; // assume A[1] is the winner... votes = 1; // A[1] has 1 "surplus" vote so far for ( i = 2; i <= N; i++ ) { if ( A[i] == winner ) { votes++; // One more vote for the assumed winner } else if ( votes > 0 ) { votes--; // One vote against the assumed winner... } else { // The assumed winner has no more surplus votes... winner = A[i]; // Pick a new assumed winner votes = 1; // A[i] has 1 "surplus" vote so far } } return winner |
|