File tree 1 file changed +40
-0
lines changed 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .Scanner ;
2
+
3
+ public class MooreVotingAlgorithm {
4
+ public static int findMajorityElement (int [] arr ) {
5
+ int candidate = -1 ;
6
+ int count = 0 ;
7
+ for (int num : arr ) {
8
+ if (count == 0 ) {
9
+ candidate = num ; // New candidate
10
+ }
11
+ count += (num == candidate ) ? 1 : -1 ;
12
+ }
13
+ count = 0 ;
14
+ for (int num : arr ) {
15
+ if (num == candidate ) {
16
+ count ++;
17
+ }
18
+ }
19
+ return (count > arr .length / 2 ) ? candidate : -1 ;
20
+ }
21
+ public static void main (String [] args ) {
22
+ Scanner sc = new Scanner (System .in );
23
+ System .out .print ("Enter the number of elements: " );
24
+ int n = sc .nextInt ();
25
+ int [] arr = new int [n ];
26
+ System .out .println ("Enter the elements:" );
27
+ for (int i = 0 ; i < n ; i ++) {
28
+ arr [i ] = sc .nextInt ();
29
+ }
30
+
31
+ int majorityElement = findMajorityElement (arr );
32
+ if (majorityElement != -1 ) {
33
+ System .out .println ("The majority element is: " + majorityElement );
34
+ } else {
35
+ System .out .println ("There is no majority element." );
36
+ }
37
+
38
+ sc .close ();
39
+ }
40
+ }
You can’t perform that action at this time.
0 commit comments