How to calculate the median of a matrix in C++

2 Answers

0 votes
#include <iostream>
#include <vector>
#include <algorithm> // For std::sort

// Function to calculate the median of a matrix
double findMedianUnsortedMatrix(const std::vector<std::vector<int>>& matrix) {
    std::vector<int> flattened;

    // Flatten the matrix into a 1D array
    for (const auto& row : matrix) {
        flattened.insert(flattened.end(), row.begin(), row.end());
    }

    // Sort the flattened array
    std::sort(flattened.begin(), flattened.end());

    // Find the median
    int n = flattened.size();
    if (n % 2 == 0) {
        // If even, median is the average of the two middle elements
        return (flattened[n / 2 - 1] + flattened[n / 2]) / 2.0;
    } else {
        // If odd, median is the middle element
        return flattened[n / 2];
    }
}

int main() {
    std::vector<std::vector<int>> matrix = {
      {5, 8, 9, 10},
      {1, 4, 6, 13},
      {7, 3, 0, 18},
      {6, 8, 9, 20},
    };

    double median = findMedianUnsortedMatrix(matrix);
    std::cout << "Median of the matrix is: " << median << std::endl;
}


/*
run:

Median of the matrix is: 7.5

*/

 



answered Oct 5, 2025 by avibootz
edited Oct 5, 2025 by avibootz
0 votes
#include <iostream>
#include <vector>
#include <algorithm> //  std::sort

double findMedianUnsortedMatrix(const std::vector<std::vector<int>>& matrix) {
    // Step 1: Flatten the matrix into a single vector
    std::vector<int> elements;
    for (const auto& row : matrix) {
        for (int val : row) {
            elements.push_back(val);
        }
    }
    
    // Step 2: Sort the elements
    std::sort(elements.begin(), elements.end());
    
    // Step 3: Calculate median
    int n = elements.size();
    if (n % 2 == 1) {
        // Odd number of elements: return middle element
        return elements[n / 2];
    } else {
        // Even number of elements: return average of two middle elements
        return (elements[n / 2 - 1] + elements[n / 2]) / 2.0;
    }
}

int main() {
    std::vector<std::vector<int>> matrix = {
      {5, 8, 9, 10},
      {1, 4, 6, 13},
      {7, 3, 0, 18},
      {6, 8, 9, 20},
    };
    
    double median = findMedianUnsortedMatrix(matrix);
    std::cout << "Median of the matrix is: " << median << std::endl;
}


/*
run:

Median: 7.5

*/

 



answered Oct 5, 2025 by avibootz
edited Oct 5, 2025 by avibootz
...