How to Find the Median of Vector Elements in C++?
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++
// C++ Program to calculate the median of a vector of // integers #include <algorithm> #include <iostream> #include <vector> using namespace std; // Function for calculating median double Median(vector< int > v, int n) { // Sort the vector sort(v.begin(), v.end()); // Check if the number of elements is odd if (n % 2 != 0) return ( double )v[n / 2]; // If the number of elements is even, return the average // of the two middle elements return ( double )(v[(n - 1) / 2] + v[n / 2]) / 2.0; } int main() { // initializing vector vector< int > v = { 5, 7, 4, 2, 6, 2, 8, 3 }; // finding size of vector int N = v.size(); // print the median cout << "Median = " << Median(v, N) << endl; return 0; } |
Output
Median = 4.5
Time Complexity: O(N log N), where N is the number of element in a vector.
Auxiliary Space: O(1)
Contact Us