I am trying to develop an algorithm in the form of a function that takes two parameters, an array and the size of the array. I want it to return an array mode, and if there are several modes, return their average value. My strategy was to take an array and sort it first. Then count all the numbers of the number. while this number occurs, add one to the counter and store this count in array m. So m holds all the counters, and another q array holds the last value that we compared.
For example: my list is {1, 1, 1, 1, 2, 2, 2} then I would have m[0] = 4 q[0] = 1 and then m[1] = 3 and q[1] = 2.
therefore, the mode q[0] = 1;
Unfortunately, I have not yet been successful. hoping someone can help.
float mode(int x[],int n) { //Copy array and sort it int y[n], temp, k = 0, counter = 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;){ for(int j = 0; j < n; j++){ while(y[i] == y[j]) { counter++; i++; } } m[k] = counter; q[k] = y[i]; i--; //i should be 1 less since it is referring to an array subscript k++; counter = 0; } }
c ++ algorithm mode
Amber roxanna
source share