-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linear-search.cpp
48 lines (41 loc) · 903 Bytes
/
linear-search.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
/*
Description: linear search using recursion
Time Complexity: O(n) where n is the number of elements in the array
*/
#include <iostream>
#include <vector>
using namespace std;
//function starts
int linearSearch(vector<int> arr, int i, int n, int target)
{
//base case
if (i == n)
{
return -1;
}
//if the ith element in the array is equal to the target, return the index
if (arr[i] == target)
{
return i;
}
//recursive function call
//i refers to the index that we will need to check the element in the array
//at every recursive call we will increment the i by 1
return linearSearch(arr, i + 1, n, target);
}
//main starts
int main()
{
vector<int> arr = {1, 2, 3, 4, 5};
int n = arr.size();
int target = 3;
cout << linearSearch(arr, 0, n, target);
return 0;
}
/*
Input:
arr = [1,2,3,4,5]
target = 3
Output:
2
*/