How to Find the Mode in a Sorted Array in C++?
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 thanmax_count
.
- If it is,
max_count
andmode
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++
// C++ program to illustrate how to find the mode in a // sorted vector #include <iostream> using namespace std; int main() { // Initialize an array with integer values int myArray[] = { 1, 2, 3, 3, 5, 5, 5, 5, 6, 7 }; int size = sizeof (myArray) / sizeof (myArray[0]); // Initialize variables to track mode int mode = -1; int curr_count = 1; int max_count = 1; // Iterate through the array to find the mode for ( int i = 1; i < size; ++i) { if (myArray[i] == myArray[i - 1]) { ++curr_count; } else { // Check if the current count is greater than // the maximum count found so far if (curr_count > max_count) { max_count = curr_count; mode = myArray[i - 1]; // Update the mode } curr_count = 1; // Reset current count for the // new element } } // Check if the last element forms the mode if (curr_count > max_count) { mode = myArray[size - 1]; } // Print the mode or a message if no mode is found if (mode != -1) { cout << "Mode is: " << mode << endl; } else { cout << "No mode found." << endl; } return 0; } |
Output
Mode is: 5
Time Complexity: O(n), where n is the elements of the sorted array.
Space Complexity: O(1)
Contact Us