Two-point Search
By using the divide-and-conquer method, the small-scale search range is applied to an ordered array.
The complexity of Time is O (log2n).
PS: The judging process of binary search algorithm can actually be described by a balanced binary tree, and the key word in the middle position can be regarded as the root node of the binary tree.
The C + + code is as follows:
1#include <iostream>2 using namespacestd;3template<classDatatype>intBinsearch (DataType key[],intn,datatype k)4 {5 intlow=0, high=n-1;6 intmid;7 while(low<=High )8 {9Mid= (Low+high)/2;Ten if(k = =Key[mid]) One { A returnmid; - } - Else if(k>Key[mid]) the { -Low=mid+1; - } - Else + { -high=mid-1; + } A } at - returnNULL; - } - - intMain () - { in intData[] = { A, at, -, the, $, the, +, the, About}; - intkey; tocout<<"Please enter the number you want to find:"; +Cin>>key; -cout<<Endl; the intresult = Binsearch (data,Ten, key); *cout<<"the number you are looking for is:"<<key<<", its location is:"<<result+1<<Endl; $ return 0;Panax Notoginseng}
View Code
Binary search of the basic algorithm