Jun 12, 2013

Problem : We have to find key element in the sorted 2D array - which is sorted row and column wise.

Brute force approach : Iterate 2D array and find whether that element is present or not. It's obvious but not a satisfactory solution. Complexity will be O(n^2) .So we can think of something in order of O(logn) or O(n).we can have several method using binary search or via zig-zag movement of matrix.One of best possible solution : (using Zig-zag movement)logic behind this is that we will start from top right corner of matrix and will reach to bottom left , so we have three possible option to move on either left , bottom or diagonally. But given matrix is sorted in row and column wise ,so we will drop the idea of moving diagonally here.Now we can move either in left or bottom which will be decided by comparing key and matrix elements.Pseudo explanation :

if ( key == matrix(row,column) ) key is found here @ (row,column) else if(key > matrix(row, column)) Move in column wise , since element which i am looking for must be below the current elements (since elements are sorted.) else Move in left direction