0

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];
}
5
  • 3
    To make it easier for answerers, or others with similar problems, please edit to add a specific problem statement — "it doesn't work" can be assumed, but how does it not work? What error message or incorrect behavior is characteristic? Commented Dec 22, 2015 at 5:10
  • For instance, the program does not work in this case: int[] c={7,6,6,5,5,8,8,8};-it returns 6 when the mode is 8. Commented Dec 22, 2015 at 5:22
  • @DanTolson It's because at the first loop only you are returning the value. So, by comparing 7's occurence and 6's occurrence it found that 6's occurrence is greater and returning the value from there only. And the loop is not running furether. Commented Dec 22, 2015 at 5:33
  • Take another array of lenght equal to the largest elements of primary array & then run a for loop to read each element of your primary array and for each element that encountered increment the value by +1 at the index of that secondary array. By the end you will have the frequency of each element then print the element with largest frequency. For more clearification see how Bucket Sort works !! Commented Dec 22, 2015 at 5:40
  • Where's the source for countRepititions? It's important we know how it returns its data. Commented Dec 22, 2015 at 15:36

1 Answer 1

2

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];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.