import java.util.Arrays;
public class MedianMatrix {
// Step 1: Flatten the matrix into a single array
public static double findMedianUnsortedMatrix(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
int total = rows * cols;
int[] elements = new int[total];
int k = 0;
for (int[] row : matrix) {
for (int val : row) {
elements[k++] = val;
}
}
// Step 2: Sort the elements
Arrays.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;
}
}
public static void main(String[] args) {
int[][] matrix = {
{5, 8, 9, 10},
{1, 4, 6, 13},
{7, 3, 0, 18},
{6, 8, 9, 20}
};
double median = findMedianUnsortedMatrix(matrix);
System.out.printf("Median of the matrix is: %.1f%n", median);
}
}
/*
run:
Median of the matrix is: 7.5
*/