Accurate binary search and Binary Search
Accurate Binary Search
It is important to accurately write binary search, because many of them are prone to errors.
There are mainly the following points:
- The initial value of right is num-1;
- Right = middle-1 each update;
- Every update of middle is left + (right-left)> 1). Note that the shift and shift operators are enclosed in brackets!
The correct procedure is as follows:
# Include <iostream> using namespace std; int isFinded (int * a, int num, int value) {int left = 0, right = num-1; int middle; while (left <= right) {middle = left + (right-left)> 1); if (a [middle] <value) left = middle + 1; else if (a [middle]> value) right = middle-1; elsereturn middle; // returned location} return-1; // not found} int main () {int a [5] = {1, 3, 5, 7, 9}; int num = 5; int value = 5; int finded = isFinded (a, num, value); cout <finded <endl; return 0 ;}