-
Notifications
You must be signed in to change notification settings - Fork 14
/
binary_search.cpp
54 lines (43 loc) · 1.01 KB
/
binary_search.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
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int bsearch(const vector<int> &arr, int l, int r, int q)
{
while (l <= r)
{
int mid = l + (r-l)/2;
if (arr[mid] == q)
return mid;
if (q < arr[mid])
{
r = mid - 1;
}
else
{
l = mid + 1;
}
}
return -1;
}
int main()
{
int query = 10;
int arr[] = {2, 4, 6, 8, 10, 12};
int N = sizeof(arr)/sizeof(arr[0]);
vector<int> v(arr, arr + N);
//sort input array
sort(v.begin(), v.end());
//std binary search
if (binary_search(v.begin(), v.end(), query))
cout << "std binary_search: found" << endl;
else
cout << "std binary_search: not found" << endl;
int idx;
idx = bsearch(v, 0, v.size(), query);
if (idx != -1)
cout << "custom binary_search: found at index " << idx << endl;
else
cout << "custom binary_search: not found" << endl;
return 0;
}