-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathhr14.cpp
50 lines (46 loc) · 907 Bytes
/
hr14.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
#include <iostream>
#include <vector>
using namespace std;
int binary_search(vector<int> x, int val, int start, int end) {
if (end == start) {
if (x[end] == val) {
cout << "yes ";
return start;
} else {
cout << "no ";
return start + 1;
}
}
else if ((end - start) == 1) {
cout << start << " " << end << endl;
if (x[start] == val) {
cout << "yes ";
return start;
}
else if (x[end] == val) {
cout << "yes ";
return end;
}
else {
cout << "no ";
return end;
}
} else {
int mid = start + (end - start) / 2;
if (x[mid] == val) {
cout << "yes ";
return mid;
}
else if (x[mid] > val) return binary_search(x, val, start, mid - 1);
else return binary_search(x, val, mid + 1, end);
}
}
int main() {
vector<int> x;
x.push_back(1);
x.push_back(2);
x.push_back(5);
x.push_back(6);
cout << binary_search(x, 2, 0, 3) + 1 << endl;
return 0;
}