1, solve the problem
Find elements from ordered data, and storage structures are typically arrays. (It is assumed that the data are sorted from small to large, as discussed below).
2. Ideas
Comparing the value of the data being looked up to the value of the intermediate element of the lookup range, the following occurs:
1) to find the data value exactly equal to the intermediate element value, put back the index of the intermediate element value.
2) to find the data value smaller than the middle element value, look for the first half of the range as the new lookup range, and execute 1) until an equal value is found.
3) to find the data value larger than the middle element value, then look for the second half of the range as the new look-up range, execute 1) until an equal value is found
4) If no equal value is found at the end, an error message is returned.
3. Code
Non-recursive mode:
intSearchindex (intData[],intIlen,intivalue) { intIbegin =0; intIend = Ilen-1; while(Ibegin <iend) { intIMiD = (Ibegin + iend)/2; if(Data[imid] = =ivalue) { returnIMiD; } Else if(Data[imid] <ivalue) {Ibegin= IMiD +1; } Else{iend= IMiD-1; } } return-1;}
Recursive mode:
intItersearchindex (intData[],intIlen,intIvalue,intIbegin,intiend) { intIMiD = (Ibegin + iend)/2; if(IMiD <0|| IMiD >=Ilen) { return-1; } if(Data[imid] = =ivalue) { returnIMiD; } Else if(Data[imid] <ivalue) { returnItersearchindex (data, Ilen, IMiD +1, iend); } Else if(Data[imid] >ivalue) { returnItersearchindex (data, Ilen, Ibegin, IMiD-1); }}
4. Analysis
Set the array data to two forks: the middle value is the root of the two fork tree, the first half is the left dial hand tree, and the second part is the right subtree. The binary lookup is exactly the number of layers where the value is located.
Queries are faster and time complexity is O (n)
Algorithm-two-point lookup (binary lookup)