
24 Majority – Who Gets Elected Class Rep? 245
Stack 1 Stack 2 Considered Action
element
empty empty B put B on Stack 2
empty B B put B on Stack 1
B B A put A on Stack 2,
remove one B from Stack 1
and put it on Stack 2
empty B,A,B A put A on Stack 2
empty B,A,B,A C put C on Stack 2
empty B,A,B,A,C D put D on Stack 2
empty B,A,B,A,C,D A put A on Stack 2
empty B,A,B,A,C,D,A A put A on Stack 1
A B,A,B,A,C,D,A A put A on Stack 1
A,A B,A,B,A,C,D,A
Indeed, the majority element A is at the top of Stack 2 when Phase 1 ends.
Phase 2 now executes as follows:
Stack 1 Stack 2 Action
A,A B,A,B,A,C,D,A The element at the top of Stack 2 is
identical to A (this must be the case,
because A was chosen to be the ele-
ment that was at the top of Stack 2
when Phase 1 ended), so remove the
two elements (D,A) from Stack 2
A,A B,A,B,A,C The element C at the top of Stack 2
is different from A, so remove one el-
ement from Stack 2 and one element
from Stack 1
A B,A,B,A The element at the top of Stack 2 is
identical to A, so remove the two ele-
ments (B,A) from Stack 2
A B,A The element at the top of Stack 2 is
identical to A, so remove the two ele-
ments (B,A) from Stack 2
A empty
Now Stack 2 is empty and Phase 2 ends. Since Stack 1 is not empty, the
algorithm correctly outputs A as the majority element. We also see that the
algorithm has made only four comparisons in Phase 2. In the first of the
four comparisons the result of the comparison was already clear in advance
(as explained by the remark in brackets), so the number of comparisons that
actually need to be performed in Phase 2 is only three.
Let us briefly sketch the analysis that shows that the refined majority
algorithm is correct. Essentially, the role of the stack in the first majority