fork(1) download
  1.  
  2. class SearchInMatrix {
  3.  
  4. /**
  5. * @param args
  6. */
  7. public static void main(String[] args) {
  8. int[][] mat = new int[][] { {10, 20, 30, 40},{15, 25, 35, 45}, {27, 29, 37, 48},{32, 33, 39, 50}};
  9. int rowcount = 4,colCount=4,key=50;
  10. for(int i=0;i<rowcount; i++)
  11. for(int j=0;j<colCount; j++)
  12. search(mat,0,rowcount-1,0,colCount-1,mat[i][j]);
  13. }
  14.  
  15. public static void search(int[][] mat,int fromRow,int toRow,int fromCol, int toCol,int key){
  16. // Search middle key.
  17. // If middle key is lesser then search lower horizontal matrix and right hand side matrix
  18. // If middle key is greater then search left vertical matrix and right hand side matrix
  19. int i = fromRow+ (toRow-fromRow )/2;
  20. int j = fromCol+ (toCol-fromCol )/2;
  21. if(mat[i][j]==key){
  22. System.out.println("Found "+key+ " at "+ i + " " + j);
  23. }else {
  24. // right hand side matrix
  25. // Provided it is different than current call
  26. if(i!=toRow || j!=fromCol){
  27. search(mat,fromRow,i,j,toCol,key);
  28. }
  29. // Special case for iteration with 1*2 matrix
  30. // mat[i][j] and mat[i][j+1] are only two elements.
  31. // So just check second element
  32. if(fromRow == toRow && fromCol +1 == toCol){
  33. if(mat[fromRow][toCol] == key){
  34. System.out.println("Found "+key+ " at "+ fromRow + " " + toCol);
  35. }
  36. }
  37.  
  38. if(mat[i][j]<key){
  39. // search lower horizontal matrix.
  40. // Provided such matrix exists
  41. if(i+1<=toRow){
  42. search(mat,i+1,toRow,fromCol,toCol,key);
  43. }else{
  44. //System.out.println("Such lower matrix doe not exisit");
  45. }
  46. }else{
  47. // left vertical matrix
  48. // Provided such matrix exists
  49. if(j-1>=fromCol){
  50. search(mat,fromRow,toRow,fromCol,j-1,key);
  51. }else{
  52. //System.out.println("Such vertical matrix doe not exisit");
  53. }
  54. }
  55.  
  56. }
  57. }
  58. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
Found 10 at 0 0
Found 20 at 0 1
Found 30 at 0 2
Found 40 at 0 3
Found 15 at 1 0
Found 25 at 1 1
Found 35 at 1 2
Found 45 at 1 3
Found 27 at 2 0
Found 29 at 2 1
Found 37 at 2 2
Found 48 at 2 3
Found 32 at 3 0
Found 33 at 3 1
Found 39 at 3 2
Found 50 at 3 3