-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linear-search-in-2d.cpp
55 lines (47 loc) · 1.08 KB
/
linear-search-in-2d.cpp
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
/*
Description: program to perform linear search in 2d array
Time complexity: O (m*n) where m is the number of rows and n refers to the number of columns
*/
#include <iostream>
#include <vector>
using namespace std;
//function starts
void linearSearch(vector<vector<int>> arr, int target)
{
//for every row
for (int i = 0; i < arr.size(); i++)
{
//for every element in the row, i.e column
for (int j = 0; j < arr[i].size(); j++)
{
//check if the element in the array is equal to the target
if (arr[i][j] == target)
{
cout << i << " " << j; //print it
return;
}
}
}
cout << "Element not found"; //else print element not found
}
//main starts
int main()
{
vector<vector<int>> arr = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}}; //array
int target = 9; //element need to be search
linearSearch(arr, target); //calling the function
return 0;
}
/*
Input:
arr = [
[1,2,3],
[4,5,6],
[7,8,9]
]
target = 9
Output: 2 2
*/