Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

java - Find the mode (most frequent value in an array) using a simple for loop?

How do I find the mode (most frequent value in an array) using a simple for loop?

The code compiles with a wrong output.

Here is what I have:

public static void mode(double [] arr)
{
    double mode=arr[0];

    for(int i = 1; i<arr.length; i++)
    {   
        if(mode==arr[i])
        {
            mode++;
        }

     }


    return mode;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First I sort the array by order and then I count occurrences of one number. No hashmaps only for loop and if statements.

My code:

static int Mode(int[] n){
    int t = 0;
    for(int i=0; i<n.length; i++){
        for(int j=1; j<n.length-i; j++){
            if(n[j-1] > n[j]){
                t = n[j-1];
                n[j-1] = n[j];
                n[j] = t;
            }
        }
    }

    int mode = n[0];
    int temp = 1;
    int temp2 = 1;
    for(int i=1;i<n.length;i++){
        if(n[i-1] == n[i]){
            temp++;
        }
        else {
            temp = 1;
        }
        if(temp >= temp2){
            mode = n[i];
            temp2 = temp;
        }
    }
    return mode;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...