Dan Tolson
Dan Tolson

Reputation: 1

Java method to return mode from array of integers

How to write a method which takes an array of integers and returns the mode.If there is more than one mode, it should return the first one

So far I have this, it works in most cases, but I don't see why exactly it returns the first occurrence of the mode.

public static int mode(int[] a) {

    int temp,temps;

    for(int i=0;i<a.length-1;i++) {
        temp=countRepititions(a,a[i]);
        temps=countRepititions(a,a[i+1]);

        if(temp>temps) {
            return a[i];
        } else if(temps>temp) {
            return a[i+1];
        }
    }

    return a[0];
}

Upvotes: 0

Views: 76

Answers (1)

thepace
thepace

Reputation: 2221

Issue:

You are comparing the count of first and second element and returning the mode without checking the complete array (if the first two elements are different).

    if(temp>temps) {  // For 766888 temp = 1 temps = 2 and 6 is returned.
        return a[i];
    } else if(temps>temp) {
        return a[i+1];
    }

Solution:

  • For the current algorithm: Traverse the complete array and store maxRepCount (max Repition Count for any integer) and maxRepIdx(Index of max repeated number) at each traversal. In the end, return a[maxRepIdx]; Complexity: O(n^2)
  • A simpler algorithm: sort the array (O(nlogn)) and then traverse the array with maxRepCount and maxRepIdx (O(n)). In the end, return a[maxRepIdx];

Upvotes: 2

Related Questions