How to Find the Median of Array in C++?
Last Updated :
21 Feb, 2024
In C++, the array is a collection of elements of the same type, In this article, we will learn how to find the median of the array in C++.
The median of the array will be the middle element if the number of elements is odd or the average of two middle elements if the number of elements is even in the sorted array.
Example:
Input:
myArray = [5, 2, 7, 3, 1, 6, 4]
Output:
median = 4
Finding Median of Array in C++
To find the median of an element, we will first sort the elements of the array in ascending order using std::sort() function.
- We then return the middle element as the median of the array if the number of elements in the array is odd, or
- return the average of two middle elements if the number of elements in the array is even.
C++ Program to Find the Median of Array
C++
#include <algorithm>
#include <iostream>
using namespace std;
double findMedian( int arr[], int n)
{
sort(arr, arr + n);
if (n % 2 != 0) {
return arr[n / 2];
}
else {
return (arr[(n - 1) / 2] + arr[n / 2]) / 2.0;
}
}
int main()
{
int arr[] = { 5, 2, 7, 3, 1, 6, 4 };
int n = sizeof (arr) / sizeof (arr[0]);
double median = findMedian(arr, n);
cout << "Median of the array is: " << median << endl;
return 0;
}
|
Output
Median of the array is: 4
Time Complexity : O(nlogn), where n is the number of elements in the array.
Space Complexity : O(1)
Share your thoughts in the comments
Please Login to comment...