Finding Median of unsorted Array in linear time using C++ STL
Given an unsorted array arr[] having N elements, the task is to find out the median of the array in linear time complexity.
Examples:
Input: N = 5, arr[] = {4, 1, 2, 6, 5}
Output: 4
Explanation:
Since N = 5, which is odd, therefore the median is the 3rd element in the sorted array.
The 3rd element in the sorted arr[] is 4.
Hence the median is 4.
Input: N = 8, arr[] = {1, 3, 4, 2, 6, 5, 8, 7}
Output: 4.5
Explanation:
Since N = 8, which is even, therefore median is the average of 4th and 5th element in the sorted array.
The 4th and 5th element in the sorted array is 4 and 5 respectively.
Hence the median is (4+5)/2 = 4.5.
Approach: The idea is to use nth_element() function in C++ STL.
- If the number of element in the array is odd, then find the (N/2)th element using nth_element() function as illustrated below and then the value at index (N/2) is the median of the given array.
nth_element(arr.begin(), arr.begin() + N/2, arr.end())
- Else find the (N/2)th and ((N – 1)/2)th element using nth_element() function as illustrated below and find the average of the values at index (N/2) and ((N – 1)/2) is the median of the given array.
nth_element(arr.begin(), arr.begin() + N/2, arr.end())
nth_element(arr.begin(), arr.begin() + (N – 1)/2, arr.end())
Below is the implementation of the above approach:
#include <bits/stdc++.h>
using namespace std;
double findMedian(vector< int > a,
int n)
{
if (n % 2 == 0) {
nth_element(a.begin(),
a.begin() + n / 2,
a.end());
nth_element(a.begin(),
a.begin() + (n - 1) / 2,
a.end());
return ( double )(a[(n - 1) / 2]
+ a[n / 2])
/ 2.0;
}
else {
nth_element(a.begin(),
a.begin() + n / 2,
a.end());
return ( double )a[n / 2];
}
}
int main()
{
vector< int > arr = { 1, 3, 4, 2,
7, 5, 8, 6 };
cout << "Median = "
<< findMedian(arr, arr.size())
<< endl;
return 0;
}
|
Time Complexity: O(N)
Auxiliary Space Complexity: O(1)
Last Updated :
07 Aug, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...