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;
The "mode" is the value that occurs most often. If no number is repeated, then there is no mode for the list. So there would be no benefit to sorting if you needed to know the "mode".
Are you sure you are not referring to the median? The median is the middle number in a set. If you have 1,2,3,4,5 the Median (middle number) is the (total_number)/2) rounded up if it is odd, 2.5 -> 3 and our median would be 3. you can only really calculate the median if your numbers are sorted. If you have an even number in a set 1,2,3,4,5,6 your mode is slots 3,4 (coincidentally also, 3,4) (total_number)/2 slot and (total_number)/2 + 1 slot, for any even array of numbers.
http://www.purplemath.com/modules/meanmode.htm
This code should give you the mode. If there are equal number of two different numbers, it will output the first of such.
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,
This had worked.
This code finds the mode in C++: