Algorithm learning----binary search algorithm

Source: Internet
Author: User

About binary search, has been confused, finally after reading some information, summed up a more practical notation.

Http://www.cnblogs.com/huang1990/archive/2013/04/02/2995284.html

http://my.oschina.net/wangliannet/blog/140480

The general principle is that the interval rule form is the same, the interval is not duplicated, the value is not missed.

The unknown origin array is source[], the array dimension is size, and the digit key to be checked.

The principle of interval division: 1, left closed right closed division method [)

Head=0,tail=size,mid= (Head+tail)/2;

Total interval is [0,size]

Start Lookup, if (Key<source[mid]), in the first half of the search, interval order for [Head,mid]; that is Tail=mid

if (Key==source[mid]), the value is found and the interval is [Mid,mid]

if (Key>source[mid]), the second half of the search, the interval order is [mid+1,tail]; that is head=mid+1

The above three sections are exactly the same as the entire unknown origin interval.

2, left closed right closed division method []

Head=0,tail=size-1,mid= (Head+tail)/2;

The total interval is [0,size-1]

Start Lookup, if (Key<source[mid]), in the first half of the search, interval order for [head,mid-1]; that is tail=mid-1

if (Key==source[mid]), the value is found and the interval is [Mid,mid]

if (Key>source[mid]), the second half of the search, the interval order is [mid+1,tail]; that is head=mid+1

The above three sections are exactly the same as the entire unknown origin interval.

Isn't that a good thing to remember?

The following is the code of the C # implementation [] form:

Http://www.cnblogs.com/huang1990/archive/2013/04/02/2995284.html

Algorithm learning----binary search algorithm

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.