Majority Element in a Array
PROGRAM
import java.util.*;
public class majority_element{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size: ");
int n = sc.nextInt();
System.out.println("Enter the elements: ");
int a[] = new int[n];
for(int i = 0; i<n; i++){
a[i] = sc.nextInt();
}
int max = n/2;
int k=0, c=0;
for(int i = 0; i<n; i++){
for(int j = 0; j<n; j++){
if(a[i] == a[j])
c++;
}
if(c>max){
k = a[i];
break;
}
}
System.out.println("The maximum number is : "+k);
}
}
EXAMPLE INPUT/OUTPUT
Input:
Enter the size:
7
Enter the elements:
3 3 4 2 4 4 2
Output:
The maximum number is : 4
LOGIC
The program first takes the size of the array and the elements as input from the user.
It initializes the variable
max
ton/2
to keep track of the threshold for the majority element.Two nested loops are used to compare each element with the rest of the array.
The count (
c
) is incremented whenever the element matches. If the count exceedsn/2
, the element is stored ink
as the majority element.The program prints the majority element.
Comments
Post a Comment