Binary search, also known as binary lookup, is a highly efficient method of finding.
"Two-point lookup Requirements": 1. Sequential storage structure must be used 2. Must be ordered by keyword size.
"Pros and cons" The advantage of binary lookup method is that the number of comparisons is small, the search speed is fast, the average performance is good, the disadvantage is that the unknown Origin table is ordered and the insertion is difficult. Therefore, the binary lookup method is suitable for an ordered list that does not change frequently and finds frequent.
"Algorithm Idea" first, the table intermediate position record of the keyword compared to the lookup keyword, if the two are equal, the search succeeds; otherwise, the table is divided into the front and the last two sub-tables using the intermediate positional records, and if the middle position record keyword is greater than the lookup keyword, the previous child table is further looked up, otherwise the next child table
Repeat the process until you find a record that satisfies the criteria, make the lookup successful, or until the child table does not exist, the lookup is unsuccessful at this time.
"Algorithmic complexity" assumes that its array length is n and its algorithm complexity is O (log (n))
The flowchart is as follows:
The test program that you write yourself is as follows:
#include <iostream> using namespace std; typedef int KEYTYPE; /************************************************************************//* Binary search method (array must be ordered)////a[] for the array to be found, The requirements are ordered; n is the length of the array; k is the keyword to find *//************************************************************************/int Binsearch (KeyType a[],int n,keytype k) {int low=0,high=n-1,mid;//Take both ends while (Low<=high) {mid= (Low+high)/2;//two divide middle position if (a[mid]==k) {return mid;} else if (a[mid]>k) {high=mid-1;} else {low=mid+1;}} return-1; }/************************************************************************//* Main function *//**************************** /int main () {int a[50],i,n,k; cout<< "number of arrays to find:"; cin>>n; cout<< "Elements of the array to be found:"; for (i=0;i<n;i++) {cin>>a[i];} cout<< "element to find:"; cin>>k; I=binsearch (A,N,K); if (i==-1) {cout<< "Cannot find what you are looking for. "<<endl;} else {cout<< "to find the element located in the" <<i+1<< "section. "<<endl;} Return0; }
The test data is as follows: