Statement

We have to search for a value **x **in a sorted matrix M. If **exists, then return its coordinates **(i, j), else return (-1, -1).

Image for post

Let us consider the above matrix as an example. In this example, we are going to search for the value 12. Since 12 is present in the matrix, the algorithm should return its coordinates (2, 1)


Simple Approach

A simple approach is to traverse all the values in the matrix and check if it is equal to 12.

Image for post

The worst case time complexity of the above algorithm will be

_O(n x m) = O(n²) __when _n = m


Efficient Approach

The above algorithm behaves worse for large values of n and m. Let us look into the efficient algorithm now.

Algorithm

1\. Start from Top Right position (0, m - 1) in the matrix M
2\. If the value is equal to x return (0, m - 1)
3\. Move one row down if the current value is less than x
4\. Move one column left if the current value is greater than x

Let us apply this algorithm into our matrix M. We are going to search for the value 12 in M

#data-structures #search-sorted-matrix #2d-binary-search #algorithms #matrix-search #algorithms

Search Sorted Matrix in Linear Time
1.35 GEEK