-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinear_search.cpp
87 lines (68 loc) · 1.29 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
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
/* Linear Search
Input - numbers in random order(integers here) and key to find
Output - Find if key is present in list of numbers or not, if present then print position whre it is present else print key not
found
Time Complexity - O(n)
*/
#include<iostream>
using namespace std;
int main()
{
int numbers[100];
int n;
int key;
int i;
cout<<"\n Enter total number of numbers : ";
cin>>n;
cout<<"\n Enter Numbers : ";
for(int i=0;i<n;i++)
{
cin>>numbers[i];
}
cout<<"\n Your Numbers : ";
for(i=0;i<n;i++)
{
cout<<" "<<numbers[i]<<" ";
}
cout<<"\n Enter Key to find : ";
cin>>key;
for(i=0;i<n;i++)
{
if(numbers[i]==key)
{
cout<<"\n Key is found at position "<<(i+1)<<"\n";
break;
}
if(i==(n-1))
{
cout<<"\n Key is not found ! \n";
break;
}
}
return 0;
}
/* OUTPUT
(base) mansi@mansi-Vostro-15-3568:~$ g++ linear_search.cpp
(base) mansi@mansi-Vostro-15-3568:~$ ./a.out
Enter total number of numbers : 5
Enter Numbers : 5
1
2
3
7
Your Numbers : 5 1 2 3 7
Enter Key to find : 7
Key is found at position 5
(base) mansi@mansi-Vostro-15-3568:~$ ./a.out
Enter total number of numbers : 6
Enter Numbers : 9
8
4
5
7
6
Your Numbers : 9 8 4 5 7 6
Enter Key to find : 1
Key is not found !
(base) mansi@mansi-Vostro-15-3568:~$
*/