How to search in a row wise and column wise increased matrix using C#?


The primitive solution for this problem is to scan all elements stored in the input matrix to search for the given key. This linear search approach costs O(MN) time if the size of the matrix is MxN.

The matrix can be viewed as a sorted one-dimensional array. If all rows in the input matrix are concatenated in top-down order, it forms a sorted one-dimensional array. And, in that case binary search algorithm is suitable for this 2D array. The below piece of code develops a function SearchRowwiseColumnWiseMatrix that takes a two-dimensional array and search key as input and returns either true or false depending upon the success or failure of search key found.

Example

public class Matrix{
   public bool SearchRowwiseColumnWiseMatrix(int[,] mat, int searchElement){
      int col = getMatrixColSize(mat);
      int start = 0;
      int last = mat.Length - 1;
      while (start <= last){
         int mid = start + (last - start) / 2;
         int mid_element = mat[mid / col, mid % col];
         if (searchElement == mid_element){
            return true;
         }
         else if (searchElement < mid_element){
            last = mid - 1;
         }
         else{
            start = mid + 1;
         }
      }
      return false;
   }
   private int getMatrixRowSize(int[,] mat){
      return mat.GetLength(0);
   }
   private int getMatrixColSize(int[,] mat){
      return mat.GetLength(1);
   }
}
static void Main(string[] args){
   Matrix m = new Matrix();
   int[,] mat = new int[3, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
   Console.WriteLine(m.SearchRowwiseColumnWiseMatrix(mat, 11));
}

Output

TRUE

Updated on: 17-Aug-2021

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements