Tuesday, March 1, 2011

Given a matrix in which each row and each column is sorted, write a method to find an element in it..One of The Most Typical Question

Assumptions:
»»Rows are sorted left to right in ascending order. Columns are sorted top to bottom in ascending order.
»»Matrix is of size MxN.
This algorithm works by elimination. Every move to the left (--col) eliminates all the elements below the current cell in that column. Likewise, every move down eliminates all the elements to the left of the cell in that row

class matrix_search
{
static boolean FindElem(int[][] mat, int elem, int M, int N)
{
int row = 0;
int col = N-1;

while (row < M && col >= 0)
{

if (mat[row][col] == elem)//done
{
return true;
}
else if (mat[row][col] > elem) //obvious as all call are sorted because all value
{
col--;
}
else // its all same as all row are sorted so if element not found in a[i][] then got
//a[i+1][] row because all all value in row[i] < row[i+1] its given
{
row++;
}

}
return false;

}


public static void main(String a[])
{

System.out.println(FindElem(new int[][]{{1,2,3,4},{5,8,9,10},{6,11,13,14},{7,12,15,16}},9,4,4));

}


}

2 comments :

Anonymous said...

please explain your thought process. how did u arrive at this solution.

Unknown said...

@Anon , as i alraedy explained the algo , u shud try with test case , if element is less then the a[i][n] tahts 1st row & last column value then we will decrement the column as column is sorted , if its greater then value we will increment the row , isn't it ? else that may be equals to given value ..thats it .just try with simple example , lst me know if u need more clarification .)

Happy Learning
Shashank