Find algorithm-binary lookup

Source: Internet
Author: User

Binary lookup, also known as binary lookup, is based on the premise that records in a linear table must be in order (usually from large to small), and linear tables must be stored sequentially.

Algorithm thought: In the ordered table, take the intermediate record as the comparison object, if the given value is equal to the key word of the intermediate record, the search succeeds;

If the given value is less than the middle record, the left half of the intermediate record continues to be searched;

If the given value is greater than the middle record's keyword, the search continues in the right half of the middle record.

Repeat the process until the lookup succeeds, or if all lookup zones are not logged, the lookup fails.

The specific code is implemented as follows:

//with recursive implementation

int BinarySearch (int[] arr, int start, int end,int key) {

int mid = (start+end)/2;

if (key = = Arr[mid]) {

return mid;

}

if (start>=end) {

return-1;

          }else if (key > Arr[mid]) {

return BinarySearch (arr, mid + 1, end, key);

} else if (Key < Arr[mid]) {

                                          return  binarysearch(arr, start, mid-1, key);
}

return-1;

}

The time complexity of binary lookups is O (LOGN).

Find algorithm-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.