Skip to content

added Boyer moore voting algo #2726

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 27, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions Others/BoyerMoore.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/* this Code is the illustration of Boyer moore's voting algorithm to
find the majority element is an array that appears more than n/2 times in an array
where "n" is the length of the array.
For more information on the algorithm refer https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
*/
package Others;
import java.util.*;

public class BoyerMoore {
public static int findmajor(int [] a){
int count=0; int cand=-1;
for(int i=0;i<a.length;i++){
if(count==0){
cand=a[i];
count=1;
}
else {
if (a[i] == cand)
count++;
else
count--;
}
}for (int i = 0; i < a.length; i++) {
if (a[i] == cand)
count++;}
if (count > (a.length / 2))
return cand;
return -1;
}
public static void main(String args[]){
Scanner input=new Scanner(System.in);
int n=input.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=input.nextInt();
}
System.out.println("the majority element is "+findmajor(a));

}
}