intcheck(int x) { return x >= 5; // 举例,寻找第一个大于等于5的数 } intbsearch(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; } intbsearch2(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
intbsearch3(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; }
intbsearch(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; elseif (arr[mid] > key) r = mid - 1; else l = mid + 1; } return-1; } intbsearch2(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; elseif (arr[mid] > key) r = mid - 1; else l = mid; } // 判断是否相等 if (arr[l] == key) return l; else return-1; } intbsearch3(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; }