Binary Search is very simple. Attention must be paid to some details about the deformation of binary search.
1. When you find the first element greater than or equal to the key or the last element smaller than or equal to the key,
The loop condition is low
However, you need to determine whether the conditions are met when the loop exits;
2. If the last condition is met,
When the lower limit is moved, low = Mid + 1 cannot be used; instead, low = mid should be used;
In this case, mid = (low + high + 1)/2,
Make sure that when the difference between low and high is 1, the system will not fall into an endless loop,
After the loop exits, the lower limit may be the result;
3. If the first condition is met,
High = mid-1 cannot be used for moving, but high = mid should be used;
In this case, mid = (low + high)/2 is used for mid calculation. Why?
After the loop exits, the upper limit may be the result;
#include <iostream>using namespace std;#define N 8int binary_search(int a[], int low, int high, int key) {while (low <= high) {int mid = (low + high)/2;if (a[mid] == key) { return mid;} else if (a[mid] > key) { high = mid - 1;} else { //a[mid] < key low = mid + 1;}}return -1;}int binary_down_bound(int a[], int low, int high, int key) {while (low < high) {int mid = (low + high + 1)/2;if (a[mid] > key) { high = mid -1;} else { //a[mid] <= key low = mid;}}if (a[low] <= key) {return low;} else { return -1;}}int binary_up_bound(int a[], int low, int high, int key) {while (low < high) {int mid = (low + high)/2;if (a[mid] < key) { low = mid +1;} else { //a[mid] >= key high = mid;}}if (a[high] >= key) {return high;} else { return -1;}}int main () { int a[] = {1,2,3,4,6,6,7,8};int pos = -1;int key = 0;cout << "intput key:";cin >> key;//pos = binary_search(a, 0, N-1, key);//pos = binary_down_bound(a, 0, N-1, key);pos = binary_up_bound(a, 0, N-1, key); cout << "binary search result:" << pos << endl;}
This article is from the "New Home Tianyan prodigy" blog, please be sure to keep this source http://tianyanshentong.blog.51cto.com/3356396/1560237
Binary Search, binary search for the first element greater than or equal to the key, binary search for the last element less than or equal to the key