O(nlogn)
整数
bool check(int mid); //检查mid是否符合要求
int binary_search1(int l, int r) // 区间[l, r]被划分成[l, mid]和[mid + 1, r]
{
while (l < r)
{
int mid = (l + r) >> 1;
if (check(mid)) //答案还可以更小
{
r = mid;
}
else
{
l = mid + 1;
}
}
return l;
}
int binary_search2(int l, int r) // 区间[l, r]被划分成[l, mid - 1]和[mid, r]
{
while (l < r)
{
int mid = (l + r + 1) >> 1;
if (check(mid)) //答案还可以更大
{
l = mid;
}
else
{
r = mid - 1;
}
}
return l;
}
浮点数
bool check(double mid);
double binary_search3(double l, double r)
{
while (r - l > eps)
{
double mid = (l + r) / 2;
if (check(mid))
{
r = mid;
}
else
{
l = mid ;
}
}
return l;
}