Two-point search also called binary search, its advantage is to find Fast, the disadvantage is that the need to find the data must be ordered sequence. The basic idea of this algorithm is to compare the data of the intermediate position of the sequence to be searched, and if it is equal, the search is successful, otherwise the sequence to be searched is divided into two parts. Next, according to the order of the search sequence and the middle element and the size of the element to find the part of the sequence to find the element may exist, the same method for the search, until it can determine whether the element to find the existence, the specific use of the following code to understand the specific.
1#include <stdio.h>2BinarySearch (intA[],intNintkey) {3 intLow =0;4 intHigh = n-1;5 while(low<=High ) {6 intMid = (low + high)/2;7 intMidval =A[mid];8 if(midval<key)9Low = mid +1;Ten Else if(midval>key) OneHigh = mid-1; A Else - returnmid; - } the return-1; - } - intMain () { - intI, Val, ret; + inta[8]={- +, A, -, -, $, $, -,98}; - for(i=0; i<8; i++) +printf"%d\t", A[i]); Aprintf"\ n Please lose the element you are looking for:"); atscanf"%d",&val); -ret = BinarySearch (A,8, Val); - if(-1==ret) -printf"lookup failed \ n"); - Else -printf ("find successful \ n"); in return 0; -}
Operation Result:
-32 98 Please enter the element you are looking for: 12 Find successful
In the above code, we succeeded in finding the search function by means of the binary search algorithm, and the implementation process is as shown.
In the lookup process shown, compare the element in the middle of the sequence to the element you are looking for, and find the element bit that you are looking for is in the left part of the sequence of the position. Next, an element on the left side of the mid is used as high to continue the two-part search, when the middle element of the mid is exactly the element to be searched for, and the search ends, returning to the index of the element. In the main function, the return value is determined to determine if the survey is successful, and if the search is successful. Print out the "Search for Success" information, otherwise output "search lost Homantin" information.
Algorithm lookup algorithm--two points lookup