Mode of an Array in Java
Mode is the
number which occurs most often in the array. Get an array of Integers arr[] with size n and find the mode value of arr[].
Example
Input 1:
7
5 2 3 2 4
Output 1:
2
Explanation:
(2 occurred
2 times and it is the most occurred compared to other numbers.)
Try your Solution
Strongly recommended to Solve it on your own, Don't directly go to the solution given below.
Program or Solution
import java.util.*;
class Mode
{
public static void main(String args[])
{
//Variable and Object Declarations
Scanner input = new Scanner(System.in);
int n;
//Getting size of Array & Declare Array arr[]
n = input.nextInt();
int arr[] = new int[n];
//Get n values to array arr[]
for(int i = 0; i<n; i++)
{
arr[i] = input.nextInt();
}
//Brute Force Approach to identify the mode (O(n^2) Time Complexity)
int max = 1;
int mode = arr[0];
for(int i=0; i<n;i++)
{
int count = 1;
for(int j=i+1; j<n; j++)
{
if(arr[i] == arr[j])
{
count+=1;
}
}
if(count > max)
{
max=count;
mode = arr[i];
}
}
System.out.print(mode);
//This program couldn't print multiple mode
}
}