Algorithm-two-point lookup (binary lookup)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.