-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmajorityElements.java
More file actions
38 lines (32 loc) · 1.06 KB
/
Copy pathmajorityElements.java
File metadata and controls
38 lines (32 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.Scanner;
public class majorityElements {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
int sizeOfArray = sc.nextInt();
int arr[] = new int[sizeOfArray];
System.out.println("Enter the elements of the array: ");
for (int i = 0; i < sizeOfArray; i++) {
arr[i] = sc.nextInt();
}
int count = 0;
int majorityElement = -1;
for(int i=0; i < sizeOfArray; i++) {
count = 0;
for(int j=0; j < sizeOfArray; j++) {
if(arr[i] == arr[j]) {
count++;
}
}
if(count > sizeOfArray / 2) {
majorityElement = arr[i];
break;
}
}
if(majorityElement == -1) {
System.out.println("There is no majority element in the array.");
} else {
System.out.println("The majority element is: " + majorityElement);
}
}
}