Skip to content

Commit ad380dc

Browse files
authored
Add Boyer moore voting algo (TheAlgorithms#2726)
1 parent b2de5c7 commit ad380dc

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Others/BoyerMoore.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/* this Code is the illustration of Boyer moore's voting algorithm to
2+
find the majority element is an array that appears more than n/2 times in an array
3+
where "n" is the length of the array.
4+
For more information on the algorithm refer https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
5+
*/
6+
package Others;
7+
import java.util.*;
8+
9+
public class BoyerMoore {
10+
public static int findmajor(int [] a){
11+
int count=0; int cand=-1;
12+
for(int i=0;i<a.length;i++){
13+
if(count==0){
14+
cand=a[i];
15+
count=1;
16+
}
17+
else {
18+
if (a[i] == cand)
19+
count++;
20+
else
21+
count--;
22+
}
23+
}for (int i = 0; i < a.length; i++) {
24+
if (a[i] == cand)
25+
count++;}
26+
if (count > (a.length / 2))
27+
return cand;
28+
return -1;
29+
}
30+
public static void main(String args[]){
31+
Scanner input=new Scanner(System.in);
32+
int n=input.nextInt();
33+
int a[]=new int[n];
34+
for(int i=0;i<n;i++){
35+
a[i]=input.nextInt();
36+
}
37+
System.out.println("the majority element is "+findmajor(a));
38+
39+
}
40+
}

0 commit comments

Comments
 (0)