Open In App

Search in a sorted 2D matrix (Stored in row major order)

Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer ‘K’ and a row-wise sorted 2-D Matrix i.e. the matrix has the following properties: 

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

The task is to find whether the integer ‘K’ is present in the matrix or not. If present then print ‘Found’ else print ‘Not found’.

Examples: 

Input: mat = {
  {1,   3,  5,  7},
  {10, 11, 16, 20},
  {23, 30, 34, 50}}
  K = 3
Output: Found

Input: mat = {
  {1,   3,  5,  7},
  {10, 11, 16, 20},
  {23, 30, 34, 50}}
  K = 13
Output: Not found

We have discussed one implementation in Search element in a sorted matrix. In this post, a better implementation is provided.

Approach: The idea is to use divide and conquer approach to solve this problem. 

  • First apply Binary Search to find the particular row i.e ‘K’ lies between the first and the last element of that row.
  • Then apply simple binary search on that row to find whether ‘K’ is present in that row or not.

Below is the implementation of the above approach: 

C++




// C++ program to find whether
// a given element is present
// in the given 2-D matrix
#include <bits/stdc++.h>
using namespace std;
 
#define M 3
#define N 4
 
// Basic binary search to
// find an element in a 1-D array
bool binarySearch1D(int arr[], int K)
{
    int low = 0;
    int high = N - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
 
        // if element found return true
        if (arr[mid] == K)
            return true;
 
        // if middle less than K then
        // skip the left part of the
        // array else skip the right part
        if (arr[mid] < K)
            low = mid + 1;
        else
            high = mid - 1;
    }
 
    // if not found return false
    return false;
}
 
// Function to search an element
// in a matrix based on
// Divide and conquer approach
bool searchMatrix(int matrix[M][N], int K)
{
    int low = 0;
    int high = M - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
 
        // if the element lies in the range
        // of this row then call
        // 1-D binary search on this row
        if (K >= matrix[mid][0]
            && K <= matrix[mid][N - 1])
            return binarySearch1D(matrix[mid], K);
 
        // if the element is less than the
        // starting element of that row then
        // search in upper rows else search
        // in the lower rows
        if (K < matrix[mid][0])
            high = mid - 1;
        else
            low = mid + 1;
    }
 
    // if not found
    return false;
}
 
// Driver code
int main()
{
    int matrix[M][N] = { { 1, 3, 5, 7 },
                         { 10, 11, 16, 20 },
                         { 23, 30, 34, 50 } };
    int K = 3;
    if (searchMatrix(matrix, K))
        cout << "Found" << endl;
    else
        cout << "Not found" << endl;
}


Java




// Java program to find whether
// a given element is present
// in the given 2-D matrix
 
public class GFG {
 
    static final int M = 3;
    static final int N = 4;
 
    // Basic binary search to
    // find an element in a 1-D array
    static boolean binarySearch1D(int arr[], int K)
    {
        int low = 0;
        int high = N - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
 
            // if element found return true
            if (arr[mid] == K) {
                return true;
            }
 
            // if middle less than K then
            // skip the left part of the
            // array else skip the right part
            if (arr[mid] < K) {
                low = mid + 1;
            }
            else {
                high = mid - 1;
            }
        }
 
        // if not found return false
        return false;
    }
 
    // Function to search an element
    // in a matrix based on
    // Divide and conquer approach
    static boolean searchMatrix(int matrix[][], int K)
    {
        int low = 0;
        int high = M - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
 
            // if the element lies in the range
            // of this row then call
            // 1-D binary search on this row
            if (K >= matrix[mid][0]
                && K <= matrix[mid][N - 1]) {
                return binarySearch1D(matrix[mid], K);
            }
 
            // if the element is less than the
            // starting element of that row then
            // search in upper rows else search
            // in the lower rows
            if (K < matrix[mid][0]) {
                high = mid - 1;
            }
            else {
                low = mid + 1;
            }
        }
 
        // if not found
        return false;
    }
 
    // Driver code
    public static void main(String args[])
    {
        int matrix[][] = { { 1, 3, 5, 7 },
                           { 10, 11, 16, 20 },
                           { 23, 30, 34, 50 } };
        int K = 3;
        if (searchMatrix(matrix, K)) {
            System.out.println("Found");
        }
        else {
            System.out.println("Not found");
        }
    }
}
 
// This code is contributed by 29AjayKumar


Python3




# Python 3 program to find whether a given
# element is present in the given 2-D matrix
 
M = 3
N = 4
 
# Basic binary search to find an element
# in a 1-D array
def binarySearch1D(arr, K):
    low = 0
    high = N - 1
    while (low <= high):
        mid = low + int((high - low) / 2)
 
        # if element found return true
        if (arr[mid] == K):
            return True
 
        # if middle less than K then skip
        # the left part of the array
        # else skip the right part
        if (arr[mid] < K):
            low = mid + 1
        else:
            high = mid - 1
 
    # if not found return false
    return False
 
# Function to search an element in a matrix
# based on Divide and conquer approach
def searchMatrix(matrix, K):
    low = 0
    high = M - 1
    while (low <= high):
        mid = low + int((high - low) / 2)
 
        # if the element lies in the range
        # of this row then call
        # 1-D binary search on this row
        if (K >= matrix[mid][0] and
            K <= matrix[mid][N - 1]):
            return binarySearch1D(matrix[mid], K)
 
        # if the element is less than the
        # starting element of that row then
        # search in upper rows else search
        # in the lower rows
        if (K < matrix[mid][0]):
            high = mid - 1
        else:
            low = mid + 1
 
    # if not found
    return False
 
# Driver code
if __name__ == '__main__':
    matrix = [[1, 3, 5, 7],
              [10, 11, 16, 20],
              [23, 30, 34, 50]]
    K = 3
    if (searchMatrix(matrix, K)):
        print("Found")
    else:
        print("Not found")
 
# This code is contributed by
# Shashank_Sharma


C#




// C# program to find whether
// a given element is present
// in the given 2-D matrix
using System;
     
class GFG
{
 
    static int M = 3;
    static int N = 4;
 
    // Basic binary search to
    // find an element in a 1-D array
    static bool binarySearch1D(int []arr, int K)
    {
        int low = 0;
        int high = N - 1;
        while (low <= high)
        {
            int mid = low + (high - low) / 2;
 
            // if element found return true
            if (arr[mid] == K)
            {
                return true;
            }
 
            // if middle less than K then
            // skip the left part of the
            // array else skip the right part
            if (arr[mid] < K)
            {
                low = mid + 1;
            }
            else
            {
                high = mid - 1;
            }
        }
 
        // if not found return false
        return false;
    }
 
    // Function to search an element
    // in a matrix based on
    // Divide and conquer approach
    static bool searchMatrix(int [,]matrix, int K)
    {
        int low = 0;
        int high = M - 1;
        while (low <= high)
        {
            int mid = low + (high - low) / 2;
 
            // if the element lies in the range
            // of this row then call
            // 1-D binary search on this row
            if (K >= matrix[mid,0]
                && K <= matrix[mid,N - 1])
            {
                return binarySearch1D(GetRow(matrix,mid), K);
            }
 
            // if the element is less than the
            // starting element of that row then
            // search in upper rows else search
            // in the lower rows
            if (K < matrix[mid,0])
            {
                high = mid - 1;
            }
            else
            {
                low = mid + 1;
            }
        }
 
        // if not found
        return false;
    }
    public static int[] GetRow(int[,] matrix, int row)
    {
        var rowLength = matrix.GetLength(1);
        var rowVector = new int[rowLength];
 
        for (var i = 0; i < rowLength; i++)
        rowVector[i] = matrix[row, i];
 
        return rowVector;
    }
     
    // Driver code
    public static void Main(String []args)
    {
        int [,]matrix = { { 1, 3, 5, 7 },
                        { 10, 11, 16, 20 },
                        { 23, 30, 34, 50 } };
        int K = 3;
        if (searchMatrix(matrix, K)) {
            Console.WriteLine("Found");
        }
        else {
        Console.WriteLine("Not found");
        }
    }
}
 
// This code contributed by Rajput-Ji


PHP




<?php
// Php program to find whether a given
// element is present in the given 2-D matrix
$M = 3;
$N = 4;
 
 
// Basic binary search to find an element
// in a 1-D array
function binarySearch1D($arr, $K)
{
     
    $low = 0;
    $high = $GLOBALS['N'] - 1;
    while ($low <= $high) {
        $mid = $low + (int)($high - $low) / 2;
 
// if element found return true
        if ($arr[$mid] == $K)
            return True;
 
// if middle less than K then skip
// the left part of the array
// else skip the right part
        if ($arr[$mid] < $K)
            $low = $mid + 1;
        else
            $high = $mid - 1;
    }
// if not found return false
    return False;
}
 
// Function to search an element in a matrix
// based on Divide and conquer approach
function searchMatrix($matrix, $K)
{
     
    $low = 0;
    $high = $GLOBALS['M']-1;
    while ($low <= $high)
    {
        $mid = $low + (int)($high - $low) / 2;
 
// if the element lies in the range
// of this row then call
// 1-D binary search on this row
        if ($K >= $matrix[$mid][0] && $K <= $matrix[$mid][$GLOBALS['N'] - 1])
            return binarySearch1D($matrix[$mid], $K);
 
// if the element is less than the
// starting element of that row then
// search in upper rows else search
// in the lower rows
        if ($K < $matrix[$mid][0])
            $high = $mid - 1;
        else
            $low = $mid + 1;
    }
 
// if not found
    return False;
}
 
// Driver code
 
$matrix = array([1, 3, 5, 7],
                [10, 11, 16, 20],
                [23, 30, 34, 50]);
$K = 3;
$M = 3;
$N = 4;
if (searchMatrix($matrix, $K))
echo "Found";
else
echo "Not found";
 
// This code is contributed by
// Srathore
?>


Javascript




<script>
 
// Javascript program to find whether
// a given element is present
// in the given 2-D matrix
 
var M = 3;
var N = 4;
 
// Basic binary search to
// find an element in a 1-D array
function binarySearch1D(arr, K)
{
    var low = 0;
    var high = N - 1;
    while (low <= high) {
        var mid = low + parseInt((high - low) / 2);
 
        // if element found return true
        if (arr[mid] == K)
            return true;
 
        // if middle less than K then
        // skip the left part of the
        // array else skip the right part
        if (arr[mid] < K)
            low = mid + 1;
        else
            high = mid - 1;
    }
 
    // if not found return false
    return false;
}
 
// Function to search an element
// in a matrix based on
// Divide and conquer approach
function searchMatrix(matrix, K)
{
    var low = 0;
    var high = M - 1;
    while (low <= high) {
        var mid = low + parseInt((high - low) / 2);
 
        // if the element lies in the range
        // of this row then call
        // 1-D binary search on this row
        if (K >= matrix[mid][0]
            && K <= matrix[mid][N - 1])
            return binarySearch1D(matrix[mid], K);
 
        // if the element is less than the
        // starting element of that row then
        // search in upper rows else search
        // in the lower rows
        if (K < matrix[mid][0])
            high = mid - 1;
        else
            low = mid + 1;
    }
 
    // if not found
    return false;
}
 
// Driver code
var matrix = [ [ 1, 3, 5, 7 ],
                     [ 10, 11, 16, 20 ],
                     [ 23, 30, 34, 50 ] ];
var K = 3;
if (searchMatrix(matrix, K))
    document.write( "Found" );
else
    document.write( "Not found" );
 
</script>


Output

Found

Complexity Analysis:

  • Time Complexity: O(logN+LogM), N & M are rows and columns of the matrix
  • Space Complexity: O(1)


Last Updated : 12 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads