Crea sito

Find the most frequent number in Array in Java

We will se how to find the most frequent number in an Array in Java, by sorting it and using only one for loop.

Before watching the code, remember that this code runs, in worst case, in O(n^2). Because the for loop runs in O(n) but the static method sort() of the Arrays.java class use QuickSort, which worst case complexity is O(n^2).

Main.java:

import java.util.Arrays;

public class Main {

	public static void main(String[] args) {

		int[] Array = { 5, -3, 9, 5, 1, 1, 5, 8, 9 };
		
		Main m = new Main();
		
		System.out.println("The most frequent number is: " + m.mostFrequentNumber(Array));
		
		
	}
	
	public int mostFrequentNumber(int[] A) {
		
		int mostFrequentNumber = 0;
		int frequencyMostFrequentNumber = 0;
		
		int currentNumber = 0;
		int frequencyCurrentNumber = 1;
		
		Arrays.sort(A);
		
		for(int i = 1; i < A.length; i++) {
			
			if(A[i] != A[i-1]) {
				currentNumber = A[i];
				frequencyCurrentNumber = 1;
			}
			
			else {
			frequencyCurrentNumber++;
			if(frequencyCurrentNumber > frequencyMostFrequentNumber) {
				mostFrequentNumber = currentNumber;
				frequencyMostFrequentNumber = frequencyCurrentNumber;
			}
		}
		}
		
		return mostFrequentNumber;
	}

}