forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinear_search.cpp
More file actions
47 lines (45 loc) · 754 Bytes
/
linear_search.cpp
File metadata and controls
47 lines (45 loc) · 754 Bytes
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
//
// C++ program to implement Linear Search
//
// The All ▲lgorithms Project
//
// https://allalgorithms.com/searches/
// https://github.com/allalgorithms/cpp
//
// Contributed by: Bharat Reddy
// Github: @Bharat-Reddy
//
#include<bits/stdc++.h>
using namespace std;
int linear_search(int a[], int n, int key)
{
int i;
for(i=0;i<n;i++)
{
if(a[i]==key) return i+1;
}
return -1;
}
int main()
{
int n,i;
cout<<"Eneter size of array : ";
cin>>n;
cout<<"Enter elements of array"<<endl;
int a[n];
for(i=0;i<n;i++)
cin>>a[i];
cout<<"Enter key to be searched : ";
int key;
cin>>key;
int res = linear_search(a,n,key);
if(res==-1)
{
cout<<key <<" not found"<<endl;
}
else
{
cout<<key<<" found at index"<<res<<endl;
}
return 0;
}