File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments