/* 二分查找/折中查找
* binsearch(int 待查找数,int 被查找数组,int 数组长度)
* 查找成功返回索引值,失败返回-1
* 限制:数组必须是"升序"的整型数组
*/
int binsearch(int x, int v[], int n){
int low, high, mid;
low = 0;
high = n - 1;
while(low <= high){
mid = (low + high) / 2;
if(x > v[mid]){
low = mid + 1;
}else if(x < v[mid]){
high = mid - 1;
}else{
return mid;
}
}
return -1;
}
网友评论