Find the most frequent element in an array in Java

In this article, we will see a program to Find the most frequent element in an array in Java. I hope, you already have some idea about array if you are familiar with Java. but still, let me tell you about array in brief.

An array is a data structure that is used to store data of the same datatype. Users can explicitly take the value of size or have to define it in the program before using it.

also, read:

An array is useful in many ways. One such example is if the user wants to store many numbers of the same datatype then he can do that by defining an array and not explicitly defining each number.

Below is the syntax of an array:

datatype[] arrayname;
or
datatype arrayname[];

Java program to get the most frequent element from an array

Now, below is our code Java code that can do our task:

import java.util.*; 

class mostFrequent{ 
  
public static void main (String[] args) { 
    
  Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array 1:");
      int size1 = sc.nextInt();
      int[] arrayEx1 = new int[size1];
      System.out.println("Enter the elements of the array1:");
      
      
      for(int i=0; i<arrayEx1.length; i++) {
         arrayEx1[i] = sc.nextInt();
      }
    
    Arrays.sort(arrayEx1); 
    int n=arrayEx1.length;
    
    int countofmax = 1;
    int temp = arrayEx1[0]; 
    int count = 1; 
    
    for (int i = 1; i < arrayEx1.length; i++) 
    { 
      if (arrayEx1[i] == arrayEx1[i - 1]) 
        count++; 
      else
      { 
        if (count > countofmax) 
        { 
          countofmax = count; 
          temp = arrayEx1[i - 1]; 
        } 
        count = 1; 
      } 
    } 
  
   
    if (count > countofmax) 
    { 
      countofmax = count; 
      temp = arrayEx1[n - 1]; 
    } 
  System.out.println("The most frequent number is:"+temp); 
  } 
} 

 

 

The output of the above program is given below:

Enter the size of the array 1:
4
Enter the elements of the array1:
2
3
1
1
The most frequent number is:1

Explanation of our program:

In this program, we have initialized a class name mostFrequent. The logic is we will initialize two counter one for the maximum count and other for the ongoing variable count.

We will first sort the array then by taking the value which is stored in the first position we will check the number of counts if it is greater than the maximum count we will interchange it. This way we will traverse through the whole array and find the most frequent one.

Complexity:O(n) where n is the number of elements in an array.

 

Leave a Reply

Your email address will not be published. Required fields are marked *