Binary search also known as binary search, the advantages are less than the number of comparisons, Find Fast, average performance, occupy less system memory;
The disadvantage is that it requires the unknown origin table to be an ordered table, and insert Delete is difficult.
Therefore, the binary lookup method is suitable for an ordered list that does not change frequently and finds frequent .
First, suppose that the elements in the table are sorted in ascending order, comparing the keywords in the middle position of the table with the lookup keywords, and if they are equal, the lookup succeeds;
Otherwise, use intermediate positional records to divide the table into the top and bottom two sub-tables, and if the middle position records a keyword that is larger than the lookup keyword, further finds the previous child table, or further finds the latter one.
Repeat the process until you find a record that satisfies the criteria to make the lookup successful, or until the child table does not exist, the lookup is unsuccessful at this time
#include <iostream>using namespacestd;intBinary_search (int*a,intNintkey) { intleft=0, right=n-1; while(left<=Right ) { intMid= (left+right) >>1; if(key==A[mid])returnmid; Else if(key<A[mid]) right=mid-1; Else Left=mid+1; } return-1;}intMain () {inta[8]={4,7,9, A, the, the, $, the}; intKey;cin>>key; cout<<binary_search (A,8, key); return 0;}
Binary lookup (binary lookup) C + +