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++
- If the size is odd, the median is the element at the middle index.
- If the size is even, the median is the average of the two middle elements.
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++ 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)
Contact Us