Find algorithm-binary lookup (also called binary search)

Source: Internet
Author: User

Brief introduction

Binary lookup (binary search), also known as binary search. The premise is that the records in the linear table must be order- critical , and the linear table must be stored sequentially .

Basic ideas

In an ordered table, the intermediate record is used as the comparison object, if the given value is equal to the key 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, and if the given value is greater than the middle record, the right half of the middle record is searched. Repeat the process until the lookup succeeds, or if all lookup zones are not logged, the lookup fails.

Advantages and Disadvantages
    1. Advantages

      Binary find, the advantages are less than the number of comparisons, Find Fast, average performance is good;

    2. Disadvantages

      Requires the unknown origin table to be an ordered table, and the insertion and deletion difficulties. Therefore, the binary lookup method is suitable for an ordered list that does not change frequently and finds frequent.

Code implementation
public  int  binary _search  (int  [] arr, int  key) {int  Low = 0 ; int  high = Arr.length -1 ; int  mid; while  (Low <= High) {mid = (low + high)/2 ; if  (Key < Arr[mid]) {High = mid-1 ; } else  if  (Key > Arr[mid]) {low = mid + 1 ; } else  {return  mid; }} return -1 ; //table does not exist key } 

Find algorithm-binary lookup (also called 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.