lab02.cpp
Problem Statement
lab02.cpp
Write a program in C++ to implement Binary Search using class, constructor, member variables, member functions, and destructor.
Source Code
cpp
#include<iostream>
using namespace std;
template <class T>
class binarySearch {
private:
T *arr;
int n;
public:
binarySearch(int size) {
n = size;
arr = new T[n];
cout << "Enter " << n << " elements: ";
for(int i = 0; i < n; i++) {
cin >> arr[i];
}
}
void searchElement(T key) {
int high = n - 1;
int low = 0;
bool found = false;
while(low <= high) {
int mid = (high + low) / 2;
if(arr[mid] == key) {
found = true;
cout << "Key found at index " << mid;
break;
}
else if(arr[mid] < key) {
low = mid + 1;
}
else if(arr[mid] > key) {
high = mid - 1;
}
}
if (!found) {
cout << "Key not found.";
}
}
~binarySearch() {
delete[] arr;
cout << "\nMemory cleared.";
}
};
int main() {
int size, key;
cout << "Enter the size: ";
cin >> size;
binarySearch<int> bs(size);
cout << "Enter the key: ";
cin >> key;
bs.searchElement(key);
return 0;
}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
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