Binary search (binary lookup)

Source: Internet
Author: User

sequential lookups do not make any assumptions about the order of the key fields in the table, unlike sequential lookups, where the records in the table are ordered alphabetically by key field, and the following three results appear in the comparison binary:

  • searchumn< List[middle].key, you do not need to consider the records between List[middle] and list[n-1], and continue to find records between List[0] and list[middle-1].
  • Searchnum=list[middle].key, at this point, the lookup succeeds and ends the lookup.
  • Searchnum>list[middle].key, you do not need to consider the records between List[0] and List[middle], and continue to find records between List[middle+1] and list[n-1].
    The complexity of time is: O(Lo g n )
    Code implementation:
//Comparison functionintCompareintOriginintSearchum) {return(Origin<searchum?-1:(Origin==searchum?0:1));}//Two-way searchintBinsearch (elementList[],intSearchum,intN) {intleft=0, right=n-1, middle; while(Left<=right) {middle= (Right-left)/2+left;Switch(Compare (List[Middle].key,searchum)] { Case-1: left=middle+1; Break; Case 0:returnMiddle; Case 1: right=middle-1; }   }}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Binary search (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.