"thought"
The main problem of binary search is to determine whether the target element targets are included in the sorted array x[0,n-1].
A binary search solves the problem by continuously tracking the range of elements that contain the target in the array (if target exists in the array).
At first, this range is the entire array, and then the range is narrowed by comparing the target with the middle item in the array and discarding half of the range. The process continues,
Until the target is found in the array or if the range containing the target is empty. In a table with n elements, a binary search needs to perform a LGN comparison operation.
To provide enough time, only 10% of professional programmers can write the program correctly.
"Positive Solution"
/********************************** Date: 2015-01-03* sjf0115* title: Binary search Algorithm * blog: ******************** /#include <iostream>using namespace std;int binarysearch (int a[], int n, int target) { if (n <= 0) { return-1; } If int start = 0,end = N-1; Two-point lookup while (start <= end) { //middle node int mid = (start + end)/2; Find if (a[mid] = = target) { return mid; } If else if (A[mid] > target) { end = mid-1; } else else{ start = mid + 1; } else }//while return-1;} int main () { int a[] = {1,2,3,4,7,9,12}; Cout<<binarysearch (a,7,9) <<endl; return 0;}
"Wrong Solution"
/********************************** Date: 2015-01-03* sjf0115* title: Binary search Algorithm * blog: ******************** /#include <iostream>using namespace std;int binarysearch (int a[], int n, int target) { if (n <= 0) { return-1; } If int start = 0,end = N-1; Two-point lookup while (Start < end) {///error //middle node int mid = (start + end)/2; Find if (a[mid] = = target) { return mid; } If else if (A[mid] > target) { end = mid-1; } else else{ start = mid + 1; } else }//while return-1;} int main () { int a[] = {1,2,3,4,7,9,12}; Cout<<binarysearch (a,7,3) <<endl; return 0;}
The error is already commented in the code. The main reason is that the target you are searching for is exactly at start = end. Examples in the code, for example.
"Wrong solution two"
/********************************** Date: 2015-01-03* sjf0115* title: Binary search Algorithm * blog: ******************** /#include <iostream>using namespace std;int binarysearch (int a[], int n, int target) { if (n <= 0) { return-1; } If int start = 0,end = N-1; Two-point lookup while (start <= end) { //middle node int mid = (start + end)/2; Find if (a[mid] = = target) { return mid; } If else if (A[mid] > target) { end = mid;// }//else else{ start = mid;//may cause errors C21/>}//else }//while return-1;} int main () { int a[] = {1,2,3,4,7,9,12}; Cout<<binarysearch (a,7,12) <<endl; return 0;}
[Algorithm] binary search algorithm