-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinear-Search.cpp
59 lines (41 loc) · 1.3 KB
/
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
49
50
51
52
53
54
55
56
57
58
59
//Including header file for using common functionalities
#include <iostream>
//Declaring function defination, to let
//compiler know that this function do exists
void Linear_Search(int [], int , int );
int rec_Linear_Search(int arr[], int first, int last, int key);
int main(){
int arr[50];
int n, key;
std::cout << "Enter the size of your array : " << std::endl;
std::cin >> n;
std::cout << "Enter your array elements : " << std::endl;
//Inputting array
for(int i=0; i < n; ++i)
std::cin >> arr[i];
std::cout << "Enter value to search : ";
std::cin >> key;
Linear_Search(arr,n,key);
return 0;
}
//Iterative approach for Linear-Search
void Linear_Search(int arr[], int size, int key){
int flag = 0;
for(int i=0; i<size; ++i)
if (arr[i] == key){
std::cout<< key << " found at index " << i << std::endl;
flag = 1;
}
if(flag == 0)
std::cout << key << " not found !" << std::endl;
}
//Recursive approach for Linear-Search
int rec_Linear_Search(int arr[], int first, int last, int key){
if(first > last)
return -1;
else if(arr[first] == key)
return first;
else if(arr[last] == key)
return last;
return rec_Linear_Search(arr,first + 1, last-1, key);
}