Binary searches (binary search)

Source: Internet
Author: User

When we look up a single order in the dictionary, we usually turn to a general position (let's say, turn to the middle) and start looking. If there's a word we want to turn to, it's good luck and the search is over. If the word we are looking for is still in front of this position, we will continue to search for this half of the previous dictionary, turn to a certain location (assuming One-fourth) and so on. This binary search works the same way. The corresponding algorithm is called binary search algorithm.

Iterative version algorithm:

//iterative binary search which returns index of elementintBinarysearchiterative (intArr[],intSizeintdata) {    intLow =0; intHigh = size-1; intmid;  while(low<=High ) {Mid= Low + (high-low)/2;//To avoid overflow by (low + high)                 if(Arr[mid] = =data)returnmid; Else        {            if(Arr[mid] <data) Low= Mid +1;//Search in right half            Else High= Mid-1;//Search in left half        }    }         return-1;}

Recursive version algorithm:

//recursive binary search which returns index of elementintBinarysearchrecursive (intArr[],intLowintHighintdata) {    if(low<=High ) {        intMID = low + (high-low)/2;//To avoid overflow             if(Arr[mid] = =data)returnmid; Else        {            if(Arr[mid] <data)//search in right half.                returnBinarysearchrecursive (arr, mid+1, high, data); Else                //search in left half.                returnBinarysearchrecursive (arr, Low, mid-1, data); }    }    return-1;}

Binary searches (binary search)

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.