1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package com.ai1tutorial.ds.algo.matrix; public class SearchElementMain { public static void main(String[] args) { int matrix[][] = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, }; int element = 13; if (!searchInSortedMatrix(matrix, element)) { System.out.println("Element " + element + " not found in matrix"); } } private static boolean searchInSortedMatrix(int[][] matrix, int element) { if (null == matrix) { return false; } int noOfRows = matrix.length; int noOfCols = matrix[0].length; int i = 0; int j = noOfCols - 1; while (i < noOfRows && j >= 0) { if (matrix[i][j] == element) { System.out.println("Element " + element + " found in matrix at (" + i + "," + j + ") index position"); return true; } if (matrix[i][j] > element) { j--; } else { i++; } } return false; } } |

1 |
Element 13 found in matrix at (2,2) index position |