-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.cpp
More file actions
45 lines (38 loc) · 938 Bytes
/
binary_search.cpp
File metadata and controls
45 lines (38 loc) · 938 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
#include <iostream>
using namespace std;
template <typename T>
int binarySearch(T array[], size_t size, T value) {
size_t middle;
size_t left = 0;
size_t right = size - 1;
while (left < right) {
middle = (left + right) / 2;
if (value < array[middle]) {
right = middle - 1;
} else if (value > array[middle]) {
left = middle + 1;
} else {
return middle;
}
return -1;
}
}
int main() {
size_t size;
int value;
cout << "Enter the size of array: ";
cin >> size;
int* array = new int[size];
cout << "Enter " << size << " integer elements of array: ";
for (size_t i = 0; i < size; ++i) {
cin >> array[i];
}
cout << "Enter a key to search: ";
cin >> value;
int index_found = binarySearch(array, size, value);
if (index_found < 0)
cout << "Value is not found!" << endl;
else
cout << "Value is found in position " << index_found << endl;
return 0;
}