-
Notifications
You must be signed in to change notification settings - Fork 266
/
BinarySearch.cpp
41 lines (33 loc) · 922 Bytes
/
BinarySearch.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
#include <iostream>
#include <vector>
using namespace std;
int binarySearch(int value, vector<int> &vec, int leftIndex, int rightIndex) {
int mid = (leftIndex + rightIndex) / 2;
if (leftIndex <= rightIndex) {
if (value > vec[mid]) {
leftIndex = mid + 1;
return binarySearch(value, vec, leftIndex, rightIndex);
} else if (value < vec[mid]) {
rightIndex = mid - 1;
return binarySearch(value, vec, leftIndex, rightIndex);
} else {
return mid;
}
} else {
return -1;
}
}
int main() {
vector<int> vec;
for (int index = 1; index <= 50; index++) {
vec.push_back(index);
}
int value = 45;
int index = binarySearch(value, vec, 0, vec.size());
if (index >= 0) {
cout << "Value " << to_string(value) << " found at position "
<< to_string(index) << endl;
} else {
cout << "Could not find the value " << to_string(value) << endl;
}
}