-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.cpp
More file actions
38 lines (37 loc) · 834 Bytes
/
BinarySearch.cpp
File metadata and controls
38 lines (37 loc) · 834 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
//Searching for the last True in TTTTTTTTTTTTTTFFFFFFFFFFFFF pattern
//change val to !val to search for last False in FFFFFFFFFTTTTTTTTT pattern
vlong b_s(vlong s, vlong e) {
while (s < e) {
vlong mid = s + (e - s + 1) / 2;
if (valid(mid))
s = mid;
else
e = mid - 1;
}
return s;
}
//Searching for the first True in FFFFFFFFTTTTTTTTT pattern
//change val to !val to search for the first False in TTTTTTTTTFFFFFFF pattern
vlong bs(vlong s, vlong e) {
while (s < e) {
vlong mid = (s + (e - s) / 2);
if (valid(mid))
e = mid;
else
s = mid + 1;
}
return s;
}
//first true double
double bs(double l, double r) {
int cnt = 0;
while (fabs(l - r) > eps && cnt < 100) {
double mid = (l + r) / 2;
if (!valid(mid))
l = mid;
else
r = mid;
cnt++;
}
return l;
}