-
Notifications
You must be signed in to change notification settings - Fork 0
/
binarySearch.cpp
62 lines (50 loc) · 967 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool binarySearch(vector<int> vec, int value)
{
int left = 0;
int right = vec.size() - 1;
while(left < right)
{
int mid = (right + left)/2;
int cvalue = vec[mid];
if(cvalue == value)
{
return true;
}
else if(cvalue > value)
{
right = mid;
}
else if(cvalue < value)
{
left = mid;
}
}
return false;
}
int main()
{
int value = 0;
int ints[] = {0,1,5,3,2,6,7,3,5};
vector<int> vec(ints, ints + sizeof(ints)/sizeof(int));
// First, we sort the vector
sort(vec.begin(), vec.end());
cout << "Sorted vector:";
for(vector<int>::iterator it = vec.begin(); it != vec.end(); it++)
{
cout << ' ' << *it;
}
cout << '\n';
if(binarySearch(vec, value))
{
cout << "Value is in vector";
} else {
cout << "Value is NOT in vector";
}
cout << '\n';
return 0;
}