-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmdsearch.cpp
127 lines (99 loc) · 2.24 KB
/
mdsearch.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include<iostream>
using namespace std;
template <class S>
class searching
{
S data[20];
S ele;
int n;
public:
searching()
{
ele='null';
n=-1;
}
int binarysearch();
int linearsearch();
void input();
};
template<class S>
void searching<S>::input()
{
cout<<"Enter size of array :";
cin>>n;
cout<<"Enter array elements: ";
for(int k=0; k < n; k++)
cin>>data[k];
cout<<"Enter the Element you want to search for :";
cin>>ele;
}
template<class S>
int searching<S>::binarysearch()
{
int beg, last, mid;
beg = 0;
last = n - 1;
while(beg <= last)
{
mid = (beg + last)/2;
if(ele == data[mid])
return mid;
else if(ele < data[mid])
last = mid - 1;
else
beg = mid + 1;
}
return -1;
}
template<class S>
int searching<S>::linearsearch()
{
int i;
for(i = 0; i < n; i++)
{
if(data[i] == ele)
return i;
}
return -1;
}
void menu()
{
cout<<"\n___________________________________________________________________________";
cout<<"\n\n\t\t1.Binary Search\t\t 2.Linear Search\n\n\t\t 3.Exit";
}
int main()
{
searching<int> s;
char choice='n';
int ch,pos;
s.input();
while (choice=='n')
{
menu();
cout<<"\nEnter the choice\n";
cin>>ch;
switch(ch)
{
case 1:
pos=s.binarysearch();
if(pos>0)
cout<<"The element is found at index no. :"<<pos;
else
cout<<"element not found";
break;
case 2:
pos=s.linearsearch();
if(pos>0)
cout<<"The element is found at index no. :"<<pos;
else
cout<<"element not found";
break;
case 3:
cout<<"are you sure you want to exit<y/n> :";
cin>>choice;
break;
default: cout<<"Wrong choice";
}
}
return 0;
}