int search(int a[], int n, int target)//迅速找到一个值
{
int l = 0, int r = n - 1;
int mid = l + r >> 1;
while(a[mid] != target){
if(a[mid] > target) mid = r;
else mid = l;
mid = l + r >> 1;
}
return mid;
}
int search(int a[], int n, int target){//找到满足某种条件的最大值
int l = 0; r = n - 1;
while(l < r)
{
int mid = l + r >> 1;
if(a[mid] > target)
r = mid - 1;
else l = mid;
}
if(a[l] == target) return l;
else return -1;
}
int search(int a[], int n, int target){//找到满足某种条件的最小值
int l = 0; r = n - 1;
while(l < r)
{
int mid = l + r >> 1;
if(a[mid] < target)
l = mid + 1;
else r = mid;
}
if(a[l] == target) return l;
else return -1;
}
二分查找的几种情况
最新推荐文章于 2024-09-08 15:12:17 发布