How to Find the Mode in a Sorted Array in C++?
Last Updated :
16 Feb, 2024
The mode of the given numbers can be defined as the value that occurs the most in the given dataset or the value with the highest frequency. In this article, we will discuss how to calculate the mode of the numbers in a sorted array in C++.
Example:
Input:
myVector = {1, 2, 2, 3, 3, 3, 4, 4, 5}
Output:
Mode = 3
Input:
myVector = {3, 5, 5, 7 , 8 , 8 , 8}
Output:
8
Calculate the Mode of a Sorted Array in C++
We can calculate the mode of the sorted array by counting the frequency of the adjacent elements as in a sorted array, all the equal numbers will be next to each other. Following is the complete approach to do that:
Approach
- Initialize an array with integer values.
- Initialize variables mode, curr_count, and max_count to track mode.
- Start iterating the array.
- If the current element is the same as the previous one,
curr_count
is incremented.
- If the current element is different, it checks if
curr_count
is greater than max_count
.
- If it is,
max_count
and mode
are updated.
curr_count
is then reset to 1 for the new element.
- Check if the last element forms the mode.
- Print the mode or a message if no mode is found.
C++ Program Calculate the Mode of a Sorted Array in C++
C++
#include <iostream>
using namespace std;
int main()
{
int myArray[] = { 1, 2, 3, 3, 5, 5, 5, 5, 6, 7 };
int size = sizeof (myArray) / sizeof (myArray[0]);
int mode = -1;
int curr_count = 1;
int max_count = 1;
for ( int i = 1; i < size; ++i) {
if (myArray[i] == myArray[i - 1]) {
++curr_count;
}
else {
if (curr_count > max_count) {
max_count = curr_count;
mode = myArray[i - 1];
}
curr_count = 1;
}
}
if (curr_count > max_count) {
mode = myArray[size - 1];
}
if (mode != -1) {
cout << "Mode is: " << mode << endl;
}
else {
cout << "No mode found." << endl;
}
return 0;
}
|
Time Complexity: O(n), where n is the elements of the sorted array.
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...