Finding the median of a column-wise sorted matrix
Here’s a Java program that solves the problem of finding the median of a column-wise sorted matrix:
import java.util.Arrays; public class MedianOfSortedMatrix { public static double findMedian(int[][] matrix) { int rows = matrix.length; int columns = matrix[0].length; // Flattening the matrix into a 1D array int[] flattened = new int[rows * columns]; int index = 0; for (int[] row : matrix) { for (int element : row) { flattened[index] = element; index++; } } // Sorting the flattened array Arrays.sort(flattened); // Finding the median if ((rows * columns) % 2 == 0) { int middleIndex1 = (rows * columns) / 2; int middleIndex2 = middleIndex1 - 1; return (flattened[middleIndex1] + flattened[middleIndex2]) / 2.0; } else { int middleIndex = (rows * columns) / 2; return flattened[middleIndex]; } } public static void main(String[] args) { int[][] matrix = { {1, 3, 5}, {2, 6, 9}, {3, 6, 9} }; double median = findMedian(matrix); System.out.println("Median: " + median); } }
In this program, we first flatten the matrix into a 1D array by iterating over each element in the matrix. Then, we sort the flattened array in ascending order using `Arrays.sort()`. After that, we calculate the median based on the size of the flattened array.
In the `main` method, we create an example matrix and call the `findMedian` method to calculate the median. Finally, we print the result to the console.
Note: This program assumes that the matrix is column-wise sorted, meaning that each column is sorted in ascending order.
No comments yet! You be the first to comment.