How to Find the Mode of Numbers in a Sorted Array in C? (original) (raw)

Last Updated : 18 Jun, 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 learn how to find the mode of all elements in a sorted array of integers in C.

**Example:

**Input:
myArray = {1, 2, 3, 3, 5, 5, 5, 5, 6, 7}

**Output:
Mode is 5

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.

Approach

C Program to Find the Mode of the Sorted Array

C `

#include <stdio.h>

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) { 
    printf("Mode is: %d" , mode) ; 
} 
else { 
    printf( "No mode found.") ; 
} 

return 0; 

}

`

**Time Complexity: O(n), where n is the elements of the sorted array.
**Space Complexity: O(1)

Similar Reads