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'?