Open In App

How to Find the Median of Sorted Vector in C++?

In C++, vectors are dynamic arrays and the median is a middle value when data is sorted in ascending order. In this article, we will learn how to find the median of all elements in a sorted vector in C++.

Example

Input:
myVector = {10, 20, 30, 40, 50};

Output:
Median is 30

Finding Median of Sorted Vector in C++

To find the median of a sorted vector in C++, first check if the size of the vector is even or odd.

C++ Program to Find the Median of Sorted Vector

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

C++
// C++ Program to illustrate how to find the median of all
// elements in a sorted vector
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

// Function to find the median of a sorted vector
int findMedian(vector<int>& vec)
{
    // Find the size of the vector
    int size = vec.size();

    if (size % 2 == 0) {
        // If the size is even
        return (vec[size / 2 - 1] + vec[size / 2]) / 2;
    }
    else {
        // If the size is odd
        return vec[size / 2];
    }
}

int main()
{

    // Intializing two vectors
    vector<int> vecOdd = { 10, 20, 30, 40, 50 };
    vector<int> vecEven = { 10, 20, 30, 40, 50, 60 };

    // Find the median of the odd vector
    int median1 = findMedian(vecOdd);
    cout << "Median of oddVec: " << median1 << endl;

    // Find the median of the even vector
    int median2 = findMedian(vecEven);
    cout << "Median of evenVec: " << median2 << endl;
    return 0;
}

Output
Median of oddVec: 30
Median of evenVec: 35

Time Complexity: O(1), as the vector is already sorted
Auxiliary Space: O(1)

Article Tags :