Search code examples
javaarraysmode

My Java method to find mode fails when my integer array is multimodal and when there's no mode


I am trying to write a java method to find the mode in an unsorted integer array. This works fine when there is only one mode within the array. But it gives out a random number when there's no mode in the array.

And also I need to make sure that my method addresses multimodal arrays as well. But I find difficulty in editing the code to return an array of modes.

public static int mode(int[] marksArray){

    int maxValue =0;int maxCount = 0;

    for (int i = 0; i < marksArray.length; ++i) {
        int count = 0;
        for (int j = 0; j < marksArray.length; ++j) {
            if (marksArray[j] == marksArray[i]) ++count;
        }
        if (count > maxCount) {
            maxCount = count;
            maxValue = marksArray[i];
        }
    }
    return maxValue;
}

Solution

  • If there's more than one mode in the array then your code returns the first, which is not unreasonable.

    To return all modes you need to maintain a list.

    static List<Integer> mode(int[] array)
    {
        List<Integer> mode = new ArrayList<>();
    
        int maxCount = 2;
        for(int i=0; i<array.length; i++)
        {               
            int count = 1;
            for(int j=i+1; j<array.length; j++)
                if(array[i] == array[j]) count++;
    
            if(count >= maxCount)
            {
                if(count > maxCount)
                {
                    mode.clear();
                    maxCount = count;
                }
                mode.add(array[i]);
            }
        }
    
        return mode;            
    }
    

    Note that there's no need to start the inner loop at 0. You can initialize count to 1 and start at i+1. Actually this is important as it means that the count for subsequent instances of array[i] will be less than the initial count, so they won't get added to the list as equal modes.

    I've edited the code to detect the case where every element of the array is distinct, in which case there's no mode.