[Algorithm] Binary Search Algorithm
[Idea]
Binary Search mainly solves the problem of determining whether the sorted array x [0, n-1] contains the target element.
Binary Search solves the problem by continuously tracking the range of the target element in the array (if the target exists in the array.
In the beginning, the range is the entire array, and then the range is reduced by comparing the target and the intermediate items in the array and dropping the half range. This process continues,
Until the target is found in the array or the range containing the target is determined to be null. In a table with n elements, perform lgn comparison for binary search.
With enough time, only 10% of professional programmers can write the program correctly.
[Positive solution]
/********************************** Date: question: Binary Search Algorithm * blog: * *********************************/# include
Using namespace std; int BinarySearch (int A [], int n, int target) {if (n <= 0) {return-1;} // if int start = 0, end = n-1; // binary search while (start <= end) {// intermediate node int mid = (start + end)/2; // find if (A [mid] = target) {return mid;} // if else if (A [mid]> target) {end = mid-1 ;} // else {start = mid + 1;} // else} // while return-1;} int main () {int A [] = {1, 2, 3, 4, 7, 9, 12}; cout <
[Troubleshooting]
/********************************** Date: question: Binary Search Algorithm * blog: * *********************************/# include
Using namespace std; int BinarySearch (int A [], int n, int target) {if (n <= 0) {return-1;} // if int start = 0, end = n-1; // binary search while (start <end) {// error // intermediate node int mid = (start + end)/2; // find if (A [mid] = target) {return mid;} // if else if (A [mid]> target) {end = mid-1 ;} // else {start = mid + 1;} // else} // while return-1;} int main () {int A [] = {1, 2, 3, 4, 7, 9, 12}; cout <
The error is in the code that has been commented out. The main reason is that the target you search for is exactly at start = end. For example, in the Code. [Solution 2]
/********************************** Date: question: Binary Search Algorithm * blog: * *********************************/# include
Using namespace std; int BinarySearch (int A [], int n, int target) {if (n <= 0) {return-1;} // if int start = 0, end = n-1; // binary search while (start <= end) {// intermediate node int mid = (start + end)/2; // find if (A [mid] = target) {return mid;} // if else if (A [mid]> target) {end = mid; // possible errors} // else {start = mid; // possible errors} // else} // while return-1;} int main () {int A [] = {1, 2, 4, 7, 9, 12}; cout <