Data structure and algorithm-two points lookup

Source: Internet
Author: User

Concept

Binary search, also known as binary lookup, is a highly efficient method of finding. It has a time complexity of O (LOGN)

Two-point lookup requirements: ordered linear table

Basic ideas

The basic idea of binary search is to divide the current search interval, and the range of the interval is narrowed down one step at a time, if a direct return is found, and the reverse is stopped until the interval has only one element.

Realize

Set R as an ordered linear table with a value increment

Implementation steps:

    • First determine the midpoint position of the interval: mid=[(Low+high)/2]
    • Then compare the value of the key to R[mid]: if it is equal, return to the current mid directly, otherwise determine the new interval operation, which is divided into two cases

①r[mid]>key indicates that key is on the left side of the interval, so low is constant, high=mid-1

②r[mid]<key indicates that key is on the right side of the interval, so high is constant, low=mid+1

    • Returns 1 if not found

Code implementation:

        public int Binsearch (int[] array, int key)        {            int. = 0, high = array. Length-1, mid;            while (low <= high)            {                mid = (low + high)/2;                int curvalue = Array[mid];                if (Curvalue = = key)                    return mid;                if (Curvalue > key)                {high                    = mid-1;                }                else                {Low                    = mid + 1;                }            }            return-1;        }

Data structure and algorithm-two points 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.