A lecturer gave this question in class: [question]
A sequence of n integers is stored in an array A[1..n]. An integer a in A is called the majority if it appears more than n/2 times in A.
An O(n) algorithm can be devised to find the majority based on the following observation: if two different elements in the original sequence are removed, then the majority in the original sequence remains the majority in the new sequence. Using this observation, or otherwise, write programming code to find the majority, if one exists, in O(n) time.
for which this solution was accepted [solution]
int findCandidate(int[] a)
{
int maj_index = 0;
int count = 1;
for (int i=1;i<a.length;i++)
{
if (a[maj_index] == a[i])
count++;
else
count--;
if (count == 0)
{
maj_index =i;
count++;
}
}
return a[maj_index];
}
int findMajority(int[] a)
{
int c = findCandidate(a);
int count = 0;
for (int i=0;i<a.length;i++)
if (a[i] == c) count++;
if (count > n/2) return c;
return -1;//just a marker - no majority found
}
I can't see how the solution provided is a dynamic solution. And I can't see how based on the wording, he pulled that code out.