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

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
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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 ` `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] ` `            ``&& K <= matrix[mid][N - 1]) ` `            ``return` `binarySearch1D(matrix[mid], K); ` ` `  `        ``// if the element is less then the ` `        ``// starting element of that row then ` `        ``// search in upper rows else search ` `        ``// in the lower rows ` `        ``if` `(K < matrix[mid]) ` `            ``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 then 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 then 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 then 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

 `= ``\$matrix``[``\$mid``] && ``\$K` `<= ``\$matrix``[``\$mid``][``\$GLOBALS``[``'N'``] - 1]) ` `            ``return` `binarySearch1D(``\$matrix``[``\$mid``], ``\$K``); ` ` `  `// if the element is less then the ` `// starting element of that row then ` `// search in upper rows else search ` `// in the lower rows ` `        ``if` `(``\$K` `< ``\$matrix``[``\$mid``]) ` `            ``\$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 ` `?> `

Output:

```Found
```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.