1,C++实现折半查找
v 中元素假设是有序的
void binary_search(vector<int> v,int x)
{
int low=0;
int high=v.size()-1;
int mid=(low+high)/2;
while(high>=low)
{
if(v[mid]==x)
{
cout<<"最终的找到位置是 "<< mid;
break;
}
else if(v[mid]>x)
{
cout<<mid<<" ";
high=mid-1;
mid=(high+low)/2;
}
else if (v[mid]<x)
{
cout<<mid<<" ";
low=mid+1;
mid=(high+low)/2;
}
}
}