Open In App

How to Find the Median of a Sorted Array in C++?

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, the median of a sorted array is the middle element if the array size is odd, or the average of the two middle elements if the array size is even. In this article, we will learn how to find the median of a sorted array in C++.

Example

Input:
myArray: {1, 2, 3, 4, 5}

Output:
Median of the Array: 3

Finding the Average of a Vector in C++

If the array size is odd, the median is the middle element. If the array size is even, the median is the average of the two middle elements. We can simply access the middle element(s) of the array by dividing the size by 2 and using the value we get as array index.

C++ Program to Find the Median of a Sorted Array

The below example demonstrates how we can find the median of a sorted array in C++.

C++
// C++ Program to illustrate how to find the median of a
// sorted array
#include <iostream>
using namespace std;

int main()
{
    // Initialize an array
    int array[] = { 1, 2, 3, 4, 5 };
    int n = sizeof(array) / sizeof(array[0]);

    // Find the median of the array
    double median;
    if (n % 2 == 0) {
        median = (array[n / 2 - 1] + array[n / 2]) / 2.0;
    }
    else {
        median = array[n / 2];
    }

    // Print the median
    cout << "Median of the Array: " << median << endl;

    return 0;
}

Output
Median of the Array: 3

Time Complexity: O(1)
Auxiliary Space: O(1)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads