using System;
class MedianMatrix
{
const int ROWSCOLS = 4;
// Step 1: Flatten the matrix into a single array
static double FindMedianUnsortedMatrix(int[,] matrix) {
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
int total = rows * cols;
int[] elements = new int[total];
int k = 0;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
elements[k++] = matrix[i, j];
// Step 2: Sort the elements
Array.Sort(elements);
// Step 3: Calculate median
if (total % 2 == 1) {
// Odd number of elements: return middle element
return elements[total / 2];
}
else {
// Even number of elements: return average of two middle elements
return (elements[total / 2 - 1] + elements[total / 2]) / 2.0;
}
}
static void Main()
{
int[,] matrix = new int[ROWSCOLS, ROWSCOLS]
{
{5, 8, 9, 10},
{1, 4, 6, 13},
{7, 3, 0, 18},
{6, 8, 9, 20}
};
double median = FindMedianUnsortedMatrix(matrix);
Console.WriteLine($"Median of the matrix is: {median:F1}");
}
}
/*
run:
Median of the matrix is: 7.5
*/