-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearch.cpp
More file actions
42 lines (38 loc) · 855 Bytes
/
binarySearch.cpp
File metadata and controls
42 lines (38 loc) · 855 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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int binary_search_helper(vector<int>& vec, int start, int end, int key)
{
if(start > end)
return -1;
int mid = start + (end - start)/2;
if(key == vec.at(mid))
{
return mid;
}
else if(key < vec.at(mid))
{
// go left
return binary_search_helper(vec, start, mid-1, key);
}
else
{
// go right
return binary_search_helper(vec, mid + 1, end, key);
}
}
void binary_search(vector<int>& vec, int key)
{
sort(vec.begin(), vec.end());
for(int i : vec)
cout << i << " ";
cout << endl;
cout << binary_search_helper(vec, 0, vec.size() - 1, key);
}
int main()
{
int key = 8;
vector<int> vec = {5, 3, 2, 1, 6, 8, 10, 22, 9};
binary_search(vec, key);
}