forked from SarahN18/Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrixSearch.cpp
More file actions
58 lines (50 loc) · 1.02 KB
/
matrixSearch.cpp
File metadata and controls
58 lines (50 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include<iostream>
using namespace std;
int main(){
int m, n;
cin >> m >> n;
int a[m][n];
for(int i = 0; i <m; i++){
for(int j = 0; j <n; j++){
cin >> a[i][j];
}
}
int target;
cin >> target;
//Linear search approach
// int key = 0;
// for(int i = 0; i <m; i++){
// for(int j = 0; j <n; j++){
// if(a[i][j] == item){
// key = 1;
// break;
// }
// }
// }
// if(key==1){
// cout<<"Element present"<<endl;
// }
// else{
// cout<<"Element not present"<<endl;
// }
//**Rows and columns are sorted
int r = 0, c = n - 1;
bool found = false;
while(r<m && c>=0){
if(a[r][c]==target){
found = true;
}
if(a[r][c]>target){
c--;
}
else{
r++;
}
}
if(found){
cout << "Element found" << endl;
}
else{
cout << "Element does not exist" << endl;
}
}