How to Find the Median of Vector Elements in C++?
Last Updated :
14 Feb, 2024
Median of a dataset is defined as the middle element when N(size of vector) is odd and the average of the middle two elements when N is even in the sorted dataset. In this article, we will learn how to find the median of all the elements of a vector in C++.
For Example
Input:
myVector = {3, 1, 6, 2, 5}
Output:
Median is: 3
Finding Median of Elements Stored in a Vector
To compute the median of all elements in a std::vector first and sort the vector using std::sort. If the number of elements in a vector is odd then the middle element is the median, otherwise for an even number of elements the average of two middle elements is a median.
C++ Program to Find Median of All Elements in Vector
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
double Median(vector< int > v, int n)
{
sort(v.begin(), v.end());
if (n % 2 != 0)
return ( double )v[n / 2];
return ( double )(v[(n - 1) / 2] + v[n / 2]) / 2.0;
}
int main()
{
vector< int > v = { 5, 7, 4, 2, 6, 2, 8, 3 };
int N = v.size();
cout << "Median = " << Median(v, N) << endl;
return 0;
}
|
Time Complexity: O(N log N), where N is the number of element in a vector.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...