Last active
December 25, 2015 18:09
-
-
Save ravichandrae/7018067 to your computer and use it in GitHub Desktop.
This program searches for the given element in a row wise and column wise sorted matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created with IntelliJ IDEA. | |
* User: Ravi | |
* Date: 10/17/13 | |
* Time: 6:41 AM | |
* To change this template use File | Settings | File Templates. | |
*/ | |
public class SearchSortedMatrix { | |
public static void main(String [] args) | |
{ | |
int [][] matrix = { | |
{1, 3, 4, 6, 9}, | |
{7, 10, 13, 15, 21}, | |
{8, 12, 14, 17, 25}, | |
{15,16, 18, 22, 26}, | |
{19,20, 23, 24, 30} | |
}; | |
matrixFind(matrix, 18); | |
matrixFind(matrix, 8); | |
matrixFind(matrix, 7); | |
matrixFind(matrix, 9); | |
matrixFind(matrix, 2); | |
matrixFind(matrix, 20); | |
matrixFind(matrix, 17); | |
} | |
public static void matrixFind(int[][]matrix, int key) | |
{ | |
//start at the top right corner | |
int i = 0; //Row index | |
int j = matrix[0].length - 1;//Column index | |
while( i < matrix.length && j >= 0 ) | |
{ | |
if( matrix[i][j] == key ) | |
{ | |
System.out.println( key + " is found at (" + i + "," + j + ")"); | |
return; | |
} | |
else if( matrix[i][j] > key ) | |
{ | |
j--;//Move to previous column | |
} | |
else | |
{ | |
i++;//Move to next row | |
} | |
} | |
System.out.println( key + " is not found!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment