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;
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.
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!
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With