4

Consider the following array with elements:

0  5  1  5  2  5

The algorithm does not return 5 as the majority element, but at the end of the first pass considers 2 as the majority element with a count of 0.

Here is the pseudo code:

num1 = array[0], count = 0;
for(int n : array){
    if (n == num1)
        count++;
    else if(count == 0)
        num1 = n;
        count = 1;
    else
        count--;
}

At the end of this iteration, num1 will contain element '2' and count will be 0. How should I make the algorithm work to return the element '5'?

truth_seeker
  • 345
  • 4
  • 14
  • 3
    *In its simplest form, the algorithm finds a majority element, if there is one: that is, an element that occurs repeatedly for **more** than half of the elements of the input.* [Wikipedia](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm) – user4003407 Dec 25 '16 at 17:21
  • 1
    Oh, I guess I missed on the part "more than half of the elements in the input". – truth_seeker Dec 25 '16 at 17:53

0 Answers0