How to Find the Median of Array in C++?
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++
// C++ Program to Find the Median of Numbers in an Array #include <algorithm> #include <iostream> using namespace std; double findMedian( int arr[], int n) { // first sort the array sort(arr, arr + n); // Check if the number is even or odd if (n % 2 != 0) { // If number of element is odd, return the middle // element return arr[n / 2]; } else { // If number of element is even, return the average // of the two middle elements 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]); // call the functiion 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)
Contact Us