I need to write a function to find the mode of a array. I\'m not good at coming up with algorithms however and I\'m hoping someone else knows how to do this.
I know
If the input array is sorted, here is the same approach as described in other answers but implemented in a different way, a better and easy to understand way.
Here is working and tested code in C++
.
int mode(vector a, int N)
{
int mode = a[0];
int mode_count = 1;
int i = 0;
while (i < N - 1) {
int cur = a[i];
int cur_count = 1;
while (a[i] == a[i + 1]) {
i++;
cur_count++;
}
if (cur_count > mode_count) {
mode_count = cur_count;
mode = a[i];
}
i++;
}
return mode;
}