forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearch.cpp
54 lines (46 loc) · 1.04 KB
/
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
42
43
44
45
46
47
48
49
50
51
52
53
54
#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;
}
}