Open In App

How to Find the Median of 2D Array in C++?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The median can be defined as the middle element of a sorted array in the case of an odd number of elements in an array and the average of the middle two elements when the number of elements in an array is even.

In this article, we will see how to calculate the median of a 2D array in C++.

Example:

Input:
myArray = { {1, 6, 5},
                     {2, 4, 6},
                    {7, 22, 9} }
Output:
Median is: 5

Finding Median of 2D Array in C++

To find the median of the 2D array, we first have to convert it to a 1D array by placing row after row. After then we will sort it and find the median in that sorted array. This approach is explained below in detail:

Approach

  1.  Create a 1D array with a size equal to the total number of elements in the 2D array.
  2. Traverse the 2D array using nested loops and add each element to flattenedArray.
  3. Sort flattenedArray in ascending order.
  4. If the total number of elements is even, the median is the average of the two middle numbers.
  5. If the total number of elements is odd, the median is the middle number.

C++ Program to Find Median of 2D Array

C++




// C++ program to find the median of a 2D array
#include <algorithm>
#include <iostream>
using namespace std;
  
// Function to find the median of a 2D array
double findMedian(int matrix[3][3], int m, int n)
{
    int mergedArray[m * n];
    int count = 0;
  
    // Merge elements into a 1D array
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            mergedArray[count++] = matrix[i][j];
        }
    }
  
    // Sort the merged array
    sort(mergedArray, mergedArray + m * n);
  
    // Calculate the median
    if ((m * n) % 2 == 0) {
        return (mergedArray[(m * n) / 2 - 1]
                + mergedArray[(m * n) / 2])
               / 2.0;
    }
    else {
        return mergedArray[(m * n) / 2];
    }
}
  
// Main function
int main()
{
    // Given 2D array
    int matrix[3][3]
        = { { 1, 6, 5 }, { 2, 4, 6 }, { 7, 22, 9 } };
  
    // Find and display the median
    cout << "Median of the 2D array is "
         << findMedian(matrix, 3, 3) << endl;
    return 0;
}


Output

Median of the 2D array is 6

Time complexity: O(n*m log(n*m) ) where n is the number of rows and m is the number of columns.
Space complexity: O(n*m)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads