I am stuck on the following question:
Given a int two-dimensional matrix
mat
of size n2 where n = 2k, search for an integer k.
The matrix's rows and columns are sorted.
If we split the matrix in quarters, each quarter is also sorted. For example, given this matrix:
-4 -2 5 9
2 5 12 13
13 20 25 25
22 24 49 57
If we split it into quarters, we can see that all of the numbers in the first quarter are equal or less than numbers in the second quarter.
In order to obtain an efficient algorithm, I thought of making a recursive binary search in on the two dimensions but it fails to search for 2
on the previous matrix.
Here's the code:
public static boolean find(int[][] mat, int x){
return find2(mat, x, 0, mat.length-1,0, mat.length-1);
}
private static boolean find2(int[][] mat, int x, int lorow, int hirow,int locol,int hicol){
if(mat.length==0) return false;
if(lorow>hirow || locol>hicol) return false;
int midrow=(lorow+hirow)/2;
int midcol=(locol+hicol)/2;
if(mat[midrow][midcol] == x ) return true;
else if(mat[midrow][midcol] < x)
return find2(mat,x,lorow,midrow,midcol+1,hicol) || find2(mat,x,midrow+1,hirow,locol,midcol) || find2(mat,x,midrow+1,hirow,midcol+1,hicol);
else
return find2(mat,x,lorow,midrow,locol,midcol-1) || find2(mat,x,midrow,hirow,locol,midcol-1) || find2(mat,x,midrow+1,hirow,midcol+1,hicol);
}
Please advise.