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;
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.
}
This code uses "map" to find out the MODE from the given array. It assumes the array is already sorted.
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.
Here is the code snippet:
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:
It run length encoding would be
It needs O(n) space.
I did it this way:
Also you can add another 25 to the list of numbers and see what happens if two numbers have the same occurrence! I hope it helps.