public class MatrixSearch {
public static boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length;
int cols = matrix[0].length;
int row = 0;
int col = cols - 1;
while (row < rows && col >= 0) {
int value = matrix[row][col];
if (value == target) {
System.out.printf("Found: i = %d j = %d%n", row, col);
return true;
} else if (value > target) {
col--;
} else {
row++;
}
}
System.out.println("Not found");
return false;
}
public static void main(String[] args) {
int[][] matrix = {
{2, 3, 5, 7, 8},
{10, 13, 17, 18, 19},
{25, 26, 30, 37, 38},
{43, 46, 50, 51, 99}
};
searchMatrix(matrix, 37);
}
}
/*
run:
Found: i = 2 j = 3
*/