File tree Expand file tree Collapse file tree 1 file changed +19
-43
lines changed Expand file tree Collapse file tree 1 file changed +19
-43
lines changed Original file line number Diff line number Diff line change
1
+ // code for linear Search
1
2
#include < iostream>
2
3
#include < vector>
3
- #include < string>
4
- #include < algorithm>
5
4
6
- std::vector< int > myarray ;
5
+ using namespace std ;
7
6
7
+ int main (){
8
+ int i,e,in,n;
9
+ vector <int > v;
10
+
11
+ cout<<" Enter the Number of elements to be inserted in Array : " ;
12
+ cin>>n;
8
13
9
- // implements linear search
10
- bool linear_search (int number)
11
- {
12
- int n = myarray.size ();
13
- for (int i = 0 ; i < n; i++)
14
- {
15
- if (number == myarray[i])
14
+ for (i=0 ;i<n;i++)
16
15
{
17
- std::cout << " found at pos: " << i + 1 << std::endl;
18
- std::cout << myarray[i] << std::endl;
19
- return true ;
16
+ cin>>in;
17
+ v.push_back (in);
20
18
}
21
- }
22
- return false ;
23
- }
24
-
25
-
26
- bool is_digits (const std::string &str)
27
- {
28
- return std::all_of (str.begin (), str.end (), ::isdigit); // C++11
29
- }
30
-
31
19
32
- int main (int argc, char const *argv[])
33
- {
34
- /* code */
20
+ cout<<" Enter the Element to be Search : " ;
21
+ cin>>e;
35
22
36
- std::string z;
37
- while ( true )
23
+ // implementation of linear search
24
+ for (i = 0 ; i < v. size (); i++ )
38
25
{
39
- std::cin>>z;
40
- if (is_digits (z))
26
+ if (e == v[i])
41
27
{
42
- int input = stoi (z) ;
43
- myarray. push_back (input) ;
28
+ cout << " Element " <<e<< " at position : " << i + 1 <<endl ;
29
+ return 0 ;
44
30
}
45
- else
46
- break ;
47
31
}
48
-
49
-
50
-
51
- std::cout<<" enter number you want to search" <<std::endl;
52
- int k;
53
- std::cin>>k;
54
- bool found = linear_search (k);
55
- if (found == false )
56
- std::cout<<" couldn't find number" <<std::endl;
32
+ cout<<" Sorry, Element is not present " ;
57
33
return 0 ;
58
34
}
You can’t perform that action at this time.
0 commit comments