Title Description:
The binary search method is to find a set of ordered numbers, pass the corresponding data, compare to find the same data as the original data, find the corresponding array subscript, failed to return-1.
Topic Analysis:
Binary search also known as binary lookup, the advantages are less than the number of comparisons, Find Fast, the average performance is good, the disadvantage is that the unknown origin table is ordered table, and insert delete difficult. Therefore, the binary lookup method is suitable for an ordered list that does not change frequently and finds frequent.
A binary lookup solves the problem of (finding a pre-sorted array): As long as the array contains T (that is, the value to look for), you can eventually find it by shrinking the range that contains T. The algorithm flow is as follows:
1. Initially, the range covers the entire array.
2. Compare the middle of the array to T, and if T is smaller than the middle of the array, continue to find the first half of the array, and vice versa, continue to the second half of the array.
3, so, each search can exclude half of the elements, the range is reduced by half. In this way, the iteration is repeated, narrowing the range, eventually finding T in the array, or determining that the range originally thought T is actually empty.
Program code:
#include <gtest/gtest.h>using namespacestd;//Recursive FunctionsTemplate<typename t>intBinarySearch (t* data,intLowintHighintkey) { if(Low >High ) { return-1; } intMid = (high + low)/2; if(Data[mid] = =key) { returnmid; } Else if(Data[mid] >key) { returnBinarySearch (data, low, mid-1, key); } Else { returnBinarySearch (data, Mid +1, high, key); }}//implementation of non-recursive functionTemplate<typename t>intBINARYSEARCH2 (t* data,intLenintkey) { intLow =0; intHigh = Len-1; while(Low <=High ) { intMid = (low + high)/2; if(Data[mid] = =key) { returnmid; } Else if(Data[mid] >key) { High= Mid-1; } Else{ Low= Mid +1; } } return-1;} TEST (Pojs, tbinarysearch) {intD1[] = {1,2,3,4,5,6,7,8}; Assert_eq (BinarySearch (D1,0,7,4),3); Assert_eq (BINARYSEARCH2 (D1,8,4),3); Assert_eq (BinarySearch (D1,0,7,9),-1); Assert_eq (BINARYSEARCH2 (D1,8,9),-1); intD2[] = {2}; Assert_eq (BinarySearch (D2,0,0,2),0); Assert_eq (BINARYSEARCH2 (D2,1,2),0); Assert_eq (BinarySearch (D2,0,0,3),-1); Assert_eq (BINARYSEARCH2 (D2,1,3),-1);}
Reference:
Http://www.cricode.com/2001.html
[Classic algorithm] binary search