Binary lookup (binary lookup) C + +

Source: Internet
Author: User

Binary search also known as binary search, the advantages are less than the number of comparisons, Find Fast, average performance, occupy less system memory;

The disadvantage is that it requires the unknown origin table to be an ordered table, and insert Delete is difficult.

Therefore, the binary lookup method is suitable for an ordered list that does not change frequently and finds frequent .

First, suppose that the elements in the table are sorted in ascending order, comparing the keywords in the middle position of the table with the lookup keywords, and if they are equal, the lookup succeeds;

Otherwise, use intermediate positional records to divide the table into the top and bottom two sub-tables, and if the middle position records a keyword that is larger than the lookup keyword, further finds the previous child table, or further finds the latter one.

Repeat the process until you find a record that satisfies the criteria to make the lookup successful, or until the child table does not exist, the lookup is unsuccessful at this time

#include <iostream>using namespacestd;intBinary_search (int*a,intNintkey) {    intleft=0, right=n-1;  while(left<=Right ) {        intMid= (left+right) >>1; if(key==A[mid])returnmid; Else if(key<A[mid]) right=mid-1; Else Left=mid+1; }    return-1;}intMain () {inta[8]={4,7,9, A, the, the, $, the}; intKey;cin>>key; cout<<binary_search (A,8, key); return 0;}

Binary lookup (binary lookup) C + +

Related Article

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.