Search code examples
javaarrayssortingmode

how to calculate mode for a sorted array in java


So I'm writing a method to calculate mode of a sorted array. But when i print out the mode value, it always comes out as 0.00, and i tried to fix it but could't. Here's my code for this method: (numRead is the passed array, num is the array length that actually have values)

public static void modeCalc(double[] numRead, int num)
    {
        double maxValue = numRead[0];
        int maxCount = 0;
        for (int i = 0; i < numRead.length; i++)
        {
            int count = 0;
            for (int j = 0; j < numRead.length; j++)
            {
                if (numRead[j] == numRead[i])
                    count++;
            }
            if (count > maxCount)
            {
                maxCount = count;
                maxValue = numRead[i];
            }
        }
        return maxValue;
    }

Any help is much appreciated!


Solution

  • This should work. You need to return a double, and you need to use num.

    class ModeArray
    {
        public static void main(String[] args) {
            double[] numRead = { 1, 2, 3, 3, 4, 4, 4, 5, 0, 0, 0, 0, 0 };
            System.out.println(modeCalc(numRead, 8));
        }
    
        public static double modeCalc(double[] numRead, int num) {
            double maxValue = numRead[0];
            int maxCount = 0;
            for (int i = 0; i < num; i++) {
                int count = 0;
                for (int j = 0; j < num; j++) {
                    if (numRead[j] == numRead[i]){
                        count++;
                    }
                }
                if (count > maxCount) {
                    maxCount = count;
                    maxValue = numRead[i];
                }
            }
            return maxValue;
        }
    }
    

    If you know the array is sorted, you should use this information.

    public static double modeCalc(double[] numRead, int num) {
        double maxValue = numRead[0];
        double lastValue = maxValue;
        int count = 1;
        int maxCount = 1;
        for (int i = 1; i < num; i++) {
            if (numRead[i] == lastValue) {
                count++;
            } else {
                count = 1;
                lastValue = numRead[i];
            }
            if (count > maxCount) {
                maxCount = count;
                maxValue = lastValue;
            }
        }
        return maxValue;
    }
    

    PS: Please don't use if-statement without braces. It makes it easier to add bugs, and harder to find them.