Search in a row wise and column wise sorted matrix

Given an n x n matrix and a number x, find the position of x in the matrix if it is present in it. Otherwise, print “Not Found”. In the given matrix, every row and column is sorted in increasing order. The designed algorithm should have linear time complexity.

Example :

Input : mat[4][4] = { {10, 20, 30, 40},
                      {15, 25, 35, 45},
                      {27, 29, 37, 48},
                      {32, 33, 39, 50}};
              x = 29
Output : Found at (2, 1)

Input : mat[4][4] = { {10, 20, 30, 40},
                      {15, 25, 35, 45},
                      {27, 29, 37, 48},
                      {32, 33, 39, 50}};
              x = 100
Output : Element not found

A simple solution is to search one by one. Time complexity of this solution is O(n2).



A better solution is to use Divide and Conquer to find the element. Time complexity of this solution is O(n1.58). Please refer this article for details.

Below is an efficient solution that works in O(n) time.
Before jumping at the solution, lets try to understand the concept that is actually allowing us to solve the problem in linear time.
Let’s start our search from the top-right corner of the array. There are three possible cases.

  1. The number we are searching for is greater than the current number. This will ensure, that all the elements in the current row is smaller than the number we are searching for as we are already at the right-most element and the row is sorted. Thus, the entire row gets eliminated and we continue our search on the next row. Here elimination means we won’t search on that row again.
  2. The number we are searching for is smaller than the current number. This will ensure, that all the elements in the current column is greater than the number we are searching for. Thus, the entire column gets eliminated and we continue our search on the previous column i.e. the column at the immediate left.
  3. The number we are searching for is equal to the current number. This will end our search.

Since, at each step, we are eliminating an entire row or column, the time complexity of the search becomes O(n).

We can also start from bottom left corner of the matrix.

Let x = element we’re trying to search for in the matrix,
….e = current element we’re processing in the array.

1) Start with top right element.
2) Loop: compare this element e with x
…i) if e = x, then return position of e, since we found x in the given matrix.
…ii) if e > x then move left to check elements smaller than e (if out of bound of matrix, then break and return false)
…iii) if e < x then move below to check elements greater than e (if out of bound of matrix, then break and return false)
3) repeat the i), ii) and iii) until you find the element or return false

Thanks to devendraiiit for suggesting below approach.

Implementation:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to search an element in row-wise
// and column-wise sorted matrix
#include <bits/stdc++.h>
  
using namespace std;
  
/* Searches the element x in mat[][]. If the 
element is found, then prints its position 
and returns true, otherwise prints "not found"
and returns false */
int search(int mat[4][4], int n, int x)
{
    if (n == 0)
        return -1;
    int smallest = a[0][0], largest = a[n - 1][n - 1];
    if (x < smallest || x > largest)
        return -1;
    // set indexes for top right element
    int i = 0, j = n - 1; 
    while (i < n && j >= 0) {
        if (mat[i][j] == x) {
            cout << "n Found at "
                 << i << ", " << j;
            return 1;
        }
        if (mat[i][j] > x)
            j--;
        else // if mat[i][j] < x
            i++;
    }
  
    cout << "n Element not found";
    return 0; // if ( i==n || j== -1 )
}
  
// Driver code
int main()
{
    int mat[4][4] = { { 10, 20, 30, 40 },
                      { 15, 25, 35, 45 },
                      { 27, 29, 37, 48 },
                      { 32, 33, 39, 50 } };
    search(mat, 4, 29);
  
    return 0;
}
  
// This code is contributed
// by Akanksha Rai(Abby_akku)

chevron_right


C

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to search an element in row-wise
// and column-wise sorted matrix
#include <stdio.h>
  
/* Searches the element x in mat[][]. If the 
element is found, then prints its position 
and returns true, otherwise prints "not found"
and returns false */
int search(int mat[4][4], int n, int x)
{
    if (n == 0)
        return -1;
    int smallest = a[0][0], largest = a[n - 1][n - 1];
    if (x < smallest || x > largest)
        return -1;
    int i = 0, j = n - 1; // set indexes for top right element
    while (i < n && j >= 0) {
        if (mat[i][j] == x) {
            printf("\n Found at %d, %d", i, j);
            return 1;
        }
        if (mat[i][j] > x)
            j--;
        else // if mat[i][j] < x
            i++;
    }
  
    printf("n Element not found");
    return 0; // if ( i==n || j== -1 )
}
  
// driver program to test above function
int main()
{
    int mat[4][4] = {
        { 10, 20, 30, 40 },
        { 15, 25, 35, 45 },
        { 27, 29, 37, 48 },
        { 32, 33, 39, 50 },
    };
    search(mat, 4, 29);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// JAVA Code for Search in a row wise and
// column wise sorted matrix
  
class GFG {
  
    /* Searches the element x in mat[][]. If the 
element is found, then prints its position 
and returns true, otherwise prints "not found"
and returns false */
    private static void search(int[][] mat, int n, int x)
    {
  
        int i = 0, j = n - 1; // set indexes for top right
        // element
  
        while (i < n && j >= 0) {
            if (mat[i][j] == x) {
                System.out.print("n Found at " + i + " " + j);
                return;
            }
            if (mat[i][j] > x)
                j--;
            else // if mat[i][j] < x
                i++;
        }
  
        System.out.print("n Element not found");
        return; // if ( i==n || j== -1 )
    }
    // driver program to test above function
    public static void main(String[] args)
    {
        int mat[][] = { { 10, 20, 30, 40 },
                        { 15, 25, 35, 45 },
                        { 27, 29, 37, 48 },
                        { 32, 33, 39, 50 } };
  
        search(mat, 4, 29);
    }
}
// This code is contributed by Arnav Kr. Mandal.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to search an element 
# in row-wise and column-wise sorted matrix
  
# Searches the element x in mat[][]. If the 
# element is found, then prints its position 
# and returns true, otherwise prints "not found"
# and returns false
def search(mat, n, x):
  
    i = 0
      
    # set indexes for top right element
    j = n - 1
    while ( i < n and j >= 0 ):
      
        if (mat[i][j] == x ):
      
            print("n Found at ", i, ", ", j)
            return 1
      
        if (mat[i][j] > x ):
            j -= 1
              
        # if mat[i][j] < x
        else
            i += 1
      
    print("Element not found")
    return 0 # if (i == n || j == -1 )
  
# Driver Code
mat = [ [10, 20, 30, 40],
        [15, 25, 35, 45],
        [27, 29, 37, 48],
        [32, 33, 39, 50] ]
search(mat, 4, 29)
  
# This code is contributed by Anant Agarwal.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Code for Search in a row wise and
// column wise sorted matrix
using System;
  
class GFG {
    /* Searches the element x in mat[][]. If the 
    element is found, then prints its position 
    and returns true, otherwise prints "not found"
    and returns false */
    private static void search(int[, ] mat,
                               int n, int x)
    {
        // set indexes for top right
        // element
        int i = 0, j = n - 1;
  
        while (i < n && j >= 0) {
            if (mat[i, j] == x) {
                Console.Write("n Found at "
                              + i + ", " + j);
                return;
            }
  
            if (mat[i, j] > x)
                j--;
            else // if mat[i][j] < x
                i++;
        }
  
        Console.Write("n Element not found");
        return; // if ( i==n || j== -1 )
    }
    // driver program to test above function
    public static void Main()
    {
  
        int[, ] mat = { { 10, 20, 30, 40 },
                        { 15, 25, 35, 45 },
                        { 27, 29, 37, 48 },
                        { 32, 33, 39, 50 } };
  
        search(mat, 4, 29);
    }
}
  
// This code is contributed by Sam007

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
// PHP program to search an 
// element in row-wise and 
// column-wise sorted matrix
  
/* Searches the element $x 
in mat[][]. If the element is 
found, then prints its position 
and returns true, otherwise prints
"not found" and returns false */
function search(&$mat, $n, $x)
{
    $i = 0;
    $j = $n - 1; // set indexes for
                // top right element
    while ($i < $n && $j >= 0)
    {
        if ($mat[$i][$j] == $x)
        {
            echo "n found at " . $i
                        ", " . $j;
            return 1;
        }
        if ($mat[$i][$j] > $x)
            $j--;
        else // if $mat[$i][$j] < $x
            $i++;
    }
      
    echo "n Element not found";
    return 0; // if ( $i==$n || $j== -1 )
}
  
// Driver Code
$mat = array(array(10, 20, 30, 40),
            array(15, 25, 35, 45),
            array(27, 29, 37, 48),
            array(32, 33, 39, 50));
search($mat, 4, 29);
  
// This code is contributed
// by ChitraNayal
?>

chevron_right


Output :

Found at 2, 1

Time Complexity: O(n)

The above approach will also work for m x n matrix (not only for n x n). Complexity would be O(m + n).

Related Article :
Search element in a sorted matrix

Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.



My Personal Notes arrow_drop_up