OC Edition binary search

Source: Internet
Author: User

Binary lookup (also called binary lookup) is a very common algorithm for finding data in arrays, which should be necessary as a programmer. Its basic idea: get the middle value of the array, divide the array into two parts, use the median value to compare with the specified value, and if the median value is greater than the specified value, find it on the left side of the array, and if the middle value is less than the specified value, find it on the right side of the array. The execution of this loop goes on and finally finds the value that matches.

Two-point search advantages: 1. Fast 2. Less than 3. Good performance of course, the shortcomings are also obvious: 1. Must be an ordered array (ascending or descending) 2. Scope of application: Apply an array of infrequently changing

The source code:

- (void) viewdidload {[Super viewdidload]; Nsarray* Array1 = @[@1,@2,@3,@4,@5,@6,@7,@9]; intresult = [Self compare:array1 target:@9]; //Print the results here to see if there are equal valuesNSLog (@"%d", result);}- (int) Compare: (Nsarray *) array target: (int) target{if(!array.count) {return-1; } unsignedintLow =0; unsignedintHigh = Array.count-1;  while(Low <=High ) {        //There will be some friends to see some people are (low + high)/2 write this, but this is a bit bad, that is, Low+high will be an integer overflow situation, if there is overflow, you divide by 2 is also useless, so can't write        intMID = Low + ((high-low)/2); //content of item mid        intnum =[Array Objectatindex:mid]; if(target = =num) {            returnLow ; }Else if(Num >target) { High= Mid-1;//find on the left}Else{ Low= Mid +1;//find on the right        }    }    return-1;//return-1 is not found}

OK, simple introduction of binary search, if there are errors, please correct them.

OC Edition 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.