-
Notifications
You must be signed in to change notification settings - Fork 158
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #8 from bilwa496/main
Created search_element_in_row_column_sorted_matrix.cpp
- Loading branch information
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
47 changes: 47 additions & 0 deletions
47
Geeks For Geeks Solutions/Binary Search/search_element_in_row_column_sorted_matrix.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
// C++ program to search an element in row-wise | ||
// and column-wise sorted matrix | ||
#include <bits/stdc++.h> | ||
|
||
using namespace std; | ||
|
||
int search(int mat[4][4], int n, int x) | ||
{ | ||
if (n == 0) | ||
return -1; | ||
|
||
int smallest = mat[0][0], largest = mat[n - 1][n - 1]; | ||
if (x < smallest || x > largest) | ||
return -1; | ||
|
||
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 | ||
i++; | ||
} | ||
|
||
cout << "n Element not found"; | ||
return 0; | ||
} | ||
|
||
// 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; | ||
} | ||
|