Find the element the occurs more than \$\dfrac{n}{2}\$ times in an input array, where \$n\$ is input array length.
I'm looking for code review, optimizations and best practices.
public final class VotingAlgorithm {
// non-instantiable.
private VotingAlgorithm() {}
/**
* Returns the number which occurs more than n/2 times.
* If such a number does not exist, then results are unpredicatable.
*
* @param a the input array
* @return the number occuring more than n/2 times.
*/
public static int maxElement(int[] a) {
int maxElementIndex = 0;
int counter = 1;
for (int i = 1; i < a.length; i++) {
if (a[maxElementIndex] == a[i]) {
counter++;
} else {
counter--;
}
if (counter == 0) {
maxElementIndex = i;
counter++;
}
}
return a[maxElementIndex];
}
public static void main(String[] args) {
int[] a1 = {1, 2, 3, 1, 1, 1};
assertEquals(1, maxElement(a1));
int[] a2 = {2, 3, 1, 1, 1, 1};
assertEquals(1, maxElement(a2));
int[] a3 = {1, 1, 1, 1, 2, 3};
assertEquals(1, maxElement(a3));
int[] a4 = {1, 2, 1, 3, 1, 1};
assertEquals(1, maxElement(a4));
int[] a5 = {1, 2, 3, 4, 1, 1, 1};
assertEquals(1, maxElement(a5));
int[] a6 = {2, 3, 4, 1, 1, 1, 1};
assertEquals(1, maxElement(a6));
int[] a7 = {1, 1, 1, 1, 2, 3, 4};
assertEquals(1, maxElement(a7));
int[] a8 = {1, 2, 1, 3, 1, 4, 1};
assertEquals(1, maxElement(a8));
}
}
int[] a9 = {1, 2, 2, 1, 3, 3, 1, 4, 4, 1, 5, 5, 5};
... what's the result? \$\endgroup\$mightGetMaxElement(...)
\$\endgroup\$