Finding the median of a row-wise sorted matrix.
Here’s an example Java program that solves the problem of finding the median of a row-wise sorted matrix:
import java.util.Arrays; public class MatrixMedianFinder { public static double findMedian(int[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; int totalElements = rows * cols; int desiredIndex = (totalElements + 1) / 2; int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int i = 0; i < rows; i++) { // Finding the minimum and maximum elements in the matrix if (matrix[i][0] < min) { min = matrix[i][0]; } if (matrix[i][cols - 1] > max) { max = matrix[i][cols - 1]; } } while (min < max) { int mid = min + (max - min) / 2; int count = 0; // Counting the number of elements less than or equal to mid for (int i = 0; i < rows; i++) { count += Arrays.binarySearch(matrix[i], mid) + 1; } if (count < desiredIndex) { min = mid + 1; } else { max = mid; } } return min; } 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); } }
This program uses binary search to find the median. It starts by finding the minimum and maximum elements in the matrix. Then, it uses binary search to find the element that has half of the total elements less than or equal to it. Finally, it returns the median value.
In the `main` method, we create a sample matrix and call the `findMedian` method to calculate the median. The result is then printed to the console.
Please note that this implementation assumes that the matrix has an odd number of elements. If the matrix has an even number of elements, you may need to modify the code accordingly to calculate the median properly.
No comments yet! You be the first to comment.