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