-
Notifications
You must be signed in to change notification settings - Fork 0
/
Search_in_2d_array_2_methods.txt
108 lines (87 loc) · 2.2 KB
/
Search_in_2d_array_2_methods.txt
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
Search_2d_array with 2 methods:-
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
void spiralprint(int arr[][10],int n,int m){
int startrow =0;
int endrow = n-1;
int startcol = 0;
int endcol = m-1;
while(startrow <= endrow && startcol <= endcol){
for(int i = startcol; i<= endcol;i++){
cout << arr[startrow][i]<<" ";
}
for(int i = startrow+1;i<=endrow;i++){
cout << arr[i][endcol]<<" ";
}
for(int i = endcol-1;i>= startcol;i--){
if(startrow==endrow)
break;
cout<<arr[endrow][i]<<" ";
}
for(int i = endrow -1;i>= startrow+1;i--){
if(startcol == endcol)
break;
cout<<arr[i][startcol]<<" ";
}
startrow++;
endrow--;
startcol++;
endcol--;
}
}
vector<int> search_in_2D(int arr[][10],int n ,int m,int key){
vector<int> v;
for(int i =0;i<n;i++){
for(int j =0;j<m;j++){
if(arr[i][j]==key){
v.push_back(i);
v.push_back(j);
return v;
}
}
}
return v;
}
pair<int,int>search_in_2D_2(int arr[][10],int n ,int m,int key){
if(key<arr[0][0] or key>arr[n-1][m-1]){
return {-1,-1};
}
int i =0;
int j = m-1;
while(i<=n-1 and j>=0){
if(arr[i][j]==key){
return {i,j};
}
else if(arr[i][j]>key){
j--;
}
else{
i++;
}
}
return {-1,-1};
}
int main(){
int arr[][10] = {{1,2,3,4},
{12,13,14,5},
{11,16,15,6},
{10,9,8,7}};
int n =4,m=4;
for(int i =0;i<n;i++){
for(int j =0;j<m;j++){
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
vector<int>v;
v = search_in_2D(arr,n,m,1);
for(int i =0;i<=v.size()-1;i++){
cout<<v[i]<<" ";
}
cout<<endl;
pair<int,int> cord = search_in_2D_2(arr,n,m,6);
cout<<cord.first<<","<<cord.second<<endl;
//spiralprint(arr,n,m);
return 0;
}