C++ Calculating the Mode of a Sorted Array

100,588

Solution 1

If the array has been sorted already, you can count the occurrences of a number at once. Then just save the number that has biggest occurrences. And you can find out the mode in only one for-loop. Otherwise, you'll have to do more than one for-loops. See a details example at the link below Find-the-Mode-of-a-Set-of-Numbers

Here is the code,

int number = array[0];
int mode = number;
int count = 1;
int countMode = 1;

for (int i=1; i<size; i++)
{
      if (array[i] == number) 
      { // count occurrences of the current number
         ++count;
      }
      else
      { // now this is a different number
            if (count > countMode) 
            {
                  countMode = count; // mode is the biggest ocurrences
                  mode = number;
            }
           count = 1; // reset count for the new number
           number = array[i];
  }
}

cout << "mode : " << mode << endl;

Solution 2

One way is that you can use Run Length encoding. In Run Length encoding, representation would be like; (Item, Its frequency).

While doing so, keep track of the maximum frequency and Item. This will give you the mode once you complete the Run Length.

for example:

 1 1  2 2 2 3 3 4 5

It run length encoding would be

 {1, 2}, {2, 3}, {3, 2}, {4, 1}, {5, 1}

It needs O(n) space.

Solution 3

There is an old adage that states "If you put 10 programmers in a room and give them the same program to code you will get 12 different results", hence my version of answering your question. It may not be as fast (I'm planning on testing it's speed versus some of the other suggestions) but I feel it is easy to understand.

#include <iostream>

using namespace std;

int main ()
{
    short z[10];
    short maxCount = 0, curCount = 0, cur = 0, most = 0;

    for (int i = 0; i < 10; i++)
        {
         cout << "Enter a number: " << endl;
         cin >> z[i];
        }

    for (int i = 0; i < 10; i++)
        {
         cur = z[i];
            for (int a = i; a < 10; a++)
                {
                 if (cur == z[a])
                    {
                     curCount++;
                     cur = z[a];
                    }
                if (curCount > maxCount)
                   {
                    maxCount = curCount;
                    most = z[a];
                   }
            }
            curCount = 0;
        }

    cout << "the mode is : " << maxCount << ", the number is: " << most << endl;
}

Solution 4

int number = array[0];
int mode = number;
int count = 1;
int countMode = 1;

for (int i=1; i<size; i++)
{
  if (array[i] == number) 
  { // count occurrences of the current number
     ++count;
  }
  else
  { // now this is a different number

       count = 1; // reset count for the new number
       number = array[i];
  }
  if (count > countMode) {
              countMode = count;
              mode = number;
  }
}

cout << "mode : " << mode << endl;

Solution 5

This is how I did it, my solution will take a sorted vector as input. It has O(n) time complexity and can work with the case where there are more than 1 "mode" number in the vector.

void findMode(vector<double> data) {

double biggestMode = 1;
vector<double> mode, numbers;
numbers.push_back(data.at(0));
mode.push_back(1);
int count = 0;
for (int i = 1; i < data.size(); i++) {
    if (data.at(i) == numbers.at(count)) {
        mode.at(count)++;
    }
    else {
        if (biggestMode < mode.at(count)) {
            biggestMode = mode.at(count);
        }
        count++;
        mode.push_back(1);
        numbers.push_back(data.at(i));
    }
}

for (int i = 0; i < mode.size(); i++) {
    if (mode.at(i) == biggestMode)
        cout << numbers.at(i) << " ";
}
cout << endl;

}

Share:
100,588
John
Author by

John

Updated on July 09, 2022

Comments

  • John
    John almost 2 years

    I have to write a C++ code that finds the median and mode of an array. I'm told that it's much easier to find the mode of an array AFTER the numbers have been sorted. I sorted the function but still cannot find the mode.

     int counter = 0;
        for (int pass = 0; pass < size - 1; pass++)
            for (int count = pass + 1; count < size; count++) {
                if (array [count] == array [pass])
                    counter++;
                cout << "The mode is: " << counter << endl; 
    
  • 1.618
    1.618 about 10 years
    Thank you, I found this useful, but I had to switch around count and countMode inside the else block for it to work.
  • Don Larynx
    Don Larynx over 9 years
    count never increases.
  • nmgeek
    nmgeek over 8 years
    There is a typo which results in a logic error: change countMode++ to count++.
  • Mike
    Mike over 7 years
    While it works (with the exception of the one typo), it only works when there is a single mode. If there is more than one mode, the output will not reflect that. Anyone viewing this answer should be aware of that and since you are most likely doing this for homework, using this solution will likely be marked incorrect do to invalid output, no matter how valid it may appear. While convoluted, @ali seems to have posted the most accurate way of getting the mode in this post
  • Parmar Kamlesh
    Parmar Kamlesh about 5 years
    not working if mode is the last number in the array. ex : int[] {1,2,3,4,5,5,6,6,6}
  • Parmar Kamlesh
    Parmar Kamlesh about 5 years
    not working if mode is the last number in the array. ex : int[] {1,2,3,4,5,5,6,6,6} put if (count > countMode) { countMode = count; mode = number;} outside of else
  • manlio
    manlio over 2 years
    Not working if mode is the last number in the array (e.g. data = {1,2,3,4,5,5,6,6,6}).
  • manlio
    manlio over 2 years
    Not working if mode is the last number in the array (e.g. arr = {1,2,3,4,5,5,6,6,6}).
  • manlio
    manlio over 2 years
    Nice, this is one of the few answers working if mode is the last number in the array. Of course it requires a sorted array.
  • manlio
    manlio over 2 years
    Not working if the mode is the last number in the array (e.g. vals[9] = {1,2,3,4,5,5,6,6,6}).