Created
June 14, 2017 05:14
-
-
Save anil477/cfdaeb3c18f1a85a5ba58f0bcc6b6e6c to your computer and use it in GitHub Desktop.
Moore’s Voting Algorithm - find the majority element in the array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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