二分查找简单又常用,但只能针对已经排序好的数据。
int binary_search(vector<int> &arr,int key)
{
int left = 0;
int right = arr.size() - 1;
while(left < right)
{
int mid = (left + right) / 2;
if(key == arr.at(mid))
{
return mid;
}
if(key > arr.at(mid))
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
}