Using C + + to find two points
For ordered tables, a binary lookup is usually used to find unknown origin records. Two-point lookup, aka binary lookup, the specific search process is: Determine the range of records to find, and then gradually narrow the scope to find or not find the record to. Its C + + implementation code looks like this:
1#include <iostream>2 using namespacestd;3 4 /*Two-point search:5 array: Arrays to find6 Low : The first position to be found for the array, typically 07 High : The length of the array-18 Searchtarget: Records to find*/9 intBinsearch (intArray[],intLowintHighintsearchtarget)Ten { One while(Low <=High ) A { - intMid = (low + high)/2; - if(Searchtarget < Array[mid])//records to find in the first half the { -High = mid-1; - } - Else if(Searchtarget > Array[mid])//records to find in the second half + { -Low = mid +1; + } A Else at { - returnMid//Find - } - } - return-1;//not found - } in - intMain () to { + inta1[6] = {1,3,5,8, One, -}; - intTargetloc = Binsearch (A1,0,7,5); thecout <<"The position of element 5 in A1 is (numbering starts from 0,-1 means not found):"<< Targetloc <<Endl; * inta2[5] = {2,3,6,7,Ten}; $Targetloc = Binsearch (A2,0,5,5);Panax Notoginsengcout <<"The position of element 5 in A2 is (numbering starts from 0,-1 means not found):"<< Targetloc <<Endl; - return 0; the
As you can see, we found the position of record 5 in the array A1, unable to find its position in the A2, the following is the result of the program running:
The position of element 5 in A1 is (numbered starting from 0,-1 means not found): 2 element 5 is in the position in A2 (numbering starts from 0, 1 indicates not found):-1
Using C + + to find two points