Monday 18 October 2021

Find the element which appears maximum number of times in an array

import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
int max = 0, count = 0;
int[] a={1,2,3,4,8,8,9,8,3,3,5,3,4,5,6,8};

//sorting array
for(int i=0;i<a.length;i++){

for(int j=i+1;j<a.length;j++){
int first=a[i];
int second=a[j];
int temp=0;

if(first>second){

temp=first;
a[i]=second;
a[j]=temp;

}
}
}
// Arrays.sort(a);
//finding highest number with times
for(int i=0;i<a.length;i++){
int num=a[i];

if(max==num){
count++;
}else if(max<num){
max=num;
count=1;

}
}

System.out.println("max number : " + max);
System.out.println("times: " + count);

}
}

OUTPUT
max number : 9
times: 1

No comments:

Post a Comment