// arr可以使用qsort方法升序排序
int Cmp(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
1.二分法返回第一个大于目标的值
int BinarySearch1(int *arr, int length, int value)
{
int left = 0;
int right = length;
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid] <= value) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
2.二分法返回第一个大于或等于目标的值
int BinarySearch2(int *arr, int length, int value)
{
int left = 0;
int right = length;
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid] < value) { // 注意这里,相比上边少了一个“=”号
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
yo peace!
网友评论