Algorithm to compute mode

前端 未结 4 1849
孤独总比滥情好
孤独总比滥情好 2021-01-12 04:42

I\'m trying to devise an algorithm in the form of a function that accepts two parameters, an array and the size of the array. I want it to return the mode of the array and i

4条回答
  •  别那么骄傲
    2021-01-12 05:09

    Here's a working version of your code. m stores the values in the array and q stores their counts. At the end it runs through all the values to get the maximal count, the sum of the modes, and the number of distinct modes.

    float mode(int x[],int n)
    {
        //Copy array and sort it
        int y[n], temp, j = 0, k = 0, m[n], q[n];
    
        for(int i = 0; i < n; i++)
            y[i] = x[i];
    
        for(int pass = 0; pass < n - 1; pass++)
            for(int pos = 0; pos < n; pos++)
                if(y[pass] > y[pos]) {
                    temp = y[pass];
                    y[pass] = y[pos];
                    y[pos] = temp;
                }   
    
        for(int i = 0; i < n;){
            j = i;
            while (y[j] == y[i]) {
              j++;
            }   
            m[k] = y[i];
            q[k] = j - i;
            k++;
            i = j;
        }   
    
        int max = 0;
        int modes_count = 0;
        int modes_sum = 0;
        for (int i=0; i < k; i++) {
            if (q[i] > max) {
                max = q[i];
                modes_count = 1;
                modes_sum = m[i];
            } else if (q[i] == max) {
                modes_count += 1;
                modes_sum += m[i];
            }   
        }   
    
        return modes_sum / modes_count;
    }
    

提交回复
热议问题