38
Find majority element using Moore's Voting algorithm
A majority element in an array of size n is an element that appears more than n/2 times and hence there is at most one such element. For example, the majority element of the array {1, 2, 1, 1, 3} is 1.
Moore's voting algorithm helps us find the majority element in an array using the following steps,
Let arr = {2, 3, 4, 2, 2, 5}, n = 6

import java.io.*;
import java.util.*;
class Test {
// T(n) = Θ(n)
// Aux space = Θ(1)
public static int findMajority(int[] arr, int n) {
int res=0, count=1;
for(int i=0; i<n; i++) {
if(arr[i] == res) {
count++;
} else {
count--;
}
if(count == 0) {
count = 1;
res = arr[i];
}
}
count = 0;
for(int i=0; i<n; i++) {
if(arr[i] == res) {
count++;
}
}
if(count < n/2) {
return -1;
}
return res;
}
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for(int i=0; i<n; i++) {
arr[i] = in.nextInt();
}
int res = findMajority(arr, n);
System.out.println(res);
}
}
2
If you have any questions about the post feel free to leave a comment below.
Follow me on twitter: @soorya_54
38