Skip to content

Commit bd19832

Browse files
Merge pull request #59 from bilwa496/patch-1
Created search_element_in_row_column_sorted_matrix.cpp
2 parents 715d795 + 05ae9b5 commit bd19832

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// C++ program to search an element in row-wise
2+
// and column-wise sorted matrix
3+
#include <bits/stdc++.h>
4+
5+
using namespace std;
6+
7+
int search(int mat[4][4], int n, int x)
8+
{
9+
if (n == 0)
10+
return -1;
11+
12+
int smallest = mat[0][0], largest = mat[n - 1][n - 1];
13+
if (x < smallest || x > largest)
14+
return -1;
15+
16+
int i = 0, j = n - 1;
17+
while (i < n && j >= 0)
18+
{
19+
if (mat[i][j] == x)
20+
{
21+
cout << "n Found at "
22+
<< i << ", " << j;
23+
return 1;
24+
}
25+
if (mat[i][j] > x)
26+
j--;
27+
28+
else
29+
i++;
30+
}
31+
32+
cout << "n Element not found";
33+
return 0;
34+
}
35+
36+
// Driver code
37+
int main()
38+
{
39+
int mat[4][4] = { { 10, 20, 30, 40 },
40+
{ 15, 25, 35, 45 },
41+
{ 27, 29, 37, 48 },
42+
{ 32, 33, 39, 50 } };
43+
search(mat, 4, 29);
44+
45+
return 0;
46+
}

0 commit comments

Comments
 (0)