查找序列中第一个满足check()条件的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int check(int x) {
return x >= 5; // 举例,寻找第一个大于等于5的数
}
int bsearch(int *arr, int n) {
int l = 0, r = n - 1;
while (l <= r) {
//int mid = l + ((r-l)>>1); // 避免溢出
int mid = l + r >> 1;
if (check(arr[mid]))
r = mid - 1;
else
l = mid + 1;
}
return l;
}
int bsearch2(int *arr, int n) {
int l = 0, r = n - 1;
while (l < r) {
int mid = l + r >> 1;
if (check(arr[mid]))
r = mid;
else
l = mid + 1;
}
return l;
}

注意:这样的代码是错误的(?):

1
2
3
4
5
6
7
8
9
10
11
12
int bsearch3(int *arr, int n) {
int l = 0, r = n - 1;
while (l < r) {
//int mid = l + ((r-l+1)>>1); // 避免溢出
int mid = l + r + 1 >> 1;
if (check(arr[mid]))
r = mid - 1; // mid被排除在区间外!
else
l = mid;
}
return l;
}

尽管从边界处理上没有问题,但是r=mid-1导致mid被排除在区间外,并且无法再次被两个指针的任何一个指向.

查找某个具体的值是否存在

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
int bsearch(int *arr, int n, int key) {
int l = 0, r = n - 1;
while (l <= r) {
//int mid = l + ((r-l+1)>>1); // 避免溢出
int mid = l + r >> 1;
if (arr[mid] == key)
return mid;
else if (arr[mid] > key)
r = mid - 1;
else
l = mid + 1;
}
return -1;
}
int bsearch2(int *arr, int n, int key) {
int l = 0, r = n - 1;
while (l < r) {
//int mid = l + ((r-l+1)>>1); // 避免溢出
int mid = l + r + 1 >> 1;
if (arr[mid] == key)
return mid;
else if (arr[mid] > key)
r = mid - 1;
else
l = mid;
}
// 判断是否相等
if (arr[l] == key)
return l;
else
return -1;
}
int bsearch3(int *arr, int n, int key) {
int l = 0, r = n - 1;
while (l < r) {
//int mid = l + ((r-l+1)>>1); // 避免溢出
int mid = l + r >> 1;
if (arr[mid] >= key)
r = mid;
else
l = mid + 1;
}
// 判断是否相等
if (arr[l] == key)
return l;
else
return -1;
}