int binary_search(int key, const std::vector<int>& sequence)
{
int L = 0;
int U = sequence.size() - 1;
while (L <= U)
{
int M = L + (U - L)/2; // avoid overflow while writing M = (L + U)/2
if (sequence[M] < key)
{
L = M + 1;
}
else if (sequence[M] > key)
{
U = M - 1;
}
else
{
return M;
}
}
return -1;
}
一直沒有規規矩矩的學懂 binary search implementation in C++
C++: std::lower_bound, upper_bound
回覆刪除Python: bisect module