考虑两件事:
1. 考虑当 = key 时该移动 l 还是 r
2. 考虑特殊情况:只有两个数且 a[l] 或 a[r] = key 时 mid 该向下取整还是向上取整来避免死循环
(1) 查找第一个和 key 值相等的元素下标
int binary_search(int a[], int n, int key) {
int l = 0, r = n - 1;
while (l < r) {
int mid = l + r >> 1; // 靠l向后移动所以向下取整
if (a[mid] >= key) r = mid;
else l = mid + 1;
}
if (a[l] == key) return l;
return -1;
}
(2) 查找最后一个和 key 值相等的元素下标
int binary_search(int a[], int n, int key) {
int l = 0, r = n - 1;
while (l < r) {
int mid = l + r + 1 >> 1; // 靠r向前移动所以向上取整
if (a[mid] <= key) l = mid;
else r = mid - 1;
}
if (a[l] == key) return l;
return -1;
}
(3) 查找第一个大于等于 key 值的元素下标
int binary_search(int a[], int n, int key) {
int l = 0, r = n - 1;
while (l < r) {
int mid = l + r >> 1;
if (a[mid] >= key) r = mid;
else l = mid + 1;
}
if (a[l] >= key) return l;
return -1;
}
(4) 查找最后一个小于等于 key 值的元素下标
int binary_search(int a[], int n, int key) {
int l = 0, r = n - 1;
while (l < r) {
int mid = l + r + 1 >> 1;
if (a[mid] <= key) l = mid;
else r = mid - 1;
}
if (a[l] <= key) return l;
return -1;
}