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