Open In App

How to Find the Mode in a Sorted Array in C++?

Last Updated : 16 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  1. Initialize an array with integer values.
  2. Initialize variables mode, curr_count, and max_count to track mode.
  3. Start iterating the array.
  4. If the current element is the same as the previous one, curr_count is incremented.
  5. If the current element is different, it checks if curr_count is greater than max_count.
    1. If it is, max_count and mode are updated.
    2. curr_count is then reset to 1 for the new element.
  6. Check if the last element forms the mode.
  7. 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)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads