#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
*/