Skip to content

Instantly share code, notes, and snippets.

@anil477
Created June 14, 2017 05:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/cfdaeb3c18f1a85a5ba58f0bcc6b6e6c to your computer and use it in GitHub Desktop.
Save anil477/cfdaeb3c18f1a85a5ba58f0bcc6b6e6c to your computer and use it in GitHub Desktop.
Moore’s Voting Algorithm - find the majority element in the array
class BoyerAlgo
{
void printMajority(int a[], int n)
{
int count = 1;
int majority = 0;
for (int i = 1; i < n; i++){
if (a[majority] == a[i]){
count++;
} else {
count--;
if (count == 0) {
majority = i;
count = 1;
}
}
}
int checkCount = 0;
for(int k:a) {
if (k==a[majority]) {
checkCount++;
}
}
if( checkCount > n/2)
System.out.println(a[majority]);
else
System.out.println(-1);
}
// Driver program to test above functions
public static void main(String[] args)
{
BoyerAlgo obj = new BoyerAlgo();
int arr[] = {1, 2, 2, 4, 2, 5, 2};
int n = arr.length;
obj.printMajority(arr, n);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment