Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Calculating the Mode of a Sorted Array

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; 
like image 223
John Avatar asked Nov 12 '13 03:11

John


People also ask

How do you find the mode of a sorted array?

We could easily find the array mode by first sorting the array and then counting successive elements that are equal. The sorting step would take O(NlogN) time to complete. The subsequent counting step would take O(N) time to find the most frequent element.

How do I calculate the mode?

To easily find the mode, put the numbers in order from least to greatest and count how many times each number occurs. The number that occurs the most is the mode!

How do you find the median of a counting sort?

Continue with the normal processing of the count sort. In the sorted array, if n is odd, then median is the middle most element of the sorted array, and if the n is even, then take middle two elements, then find the average of them to get the median. Store the value into another separate variable named median.


1 Answers

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;
}
like image 115
Scott A Avatar answered Oct 21 '22 16:10

Scott A