Binary search also known as binary lookup, the advantages are less than the number of comparisons, Find Fast, the average performance is good, the disadvantage is that the unknown origin table is ordered table, and insert delete difficult. Therefore, the binary lookup method is suitable for an ordered list that does not change frequently and finds frequent.
Two kinds of implementations of binary lookup method
binary look-up method thought :
In an ordered table, there are three scenarios where the value of the data to be looked up is compared to the median value of the lookup range:
1) To find the data value exactly equal to the intermediate element value, put back the index of the intermediate element value.
2) The data value to find is smaller than the middle element value, then the first half of the entire look-up range is used as the new look-up range, performing 1 ) until an equal value is found.
3) to find the data value larger than the middle element value, the second half of the entire look-up range is used as the new lookup range, which executes 1 ) until an equal value is found
4) if no equal value is found at the end, an error message is returned.
According to the binary tree to understand : The median is two fork tree root, the first half of the left dial hand tree, the second half is the right sub-tree. The binary lookup is exactly the number of layers where the value is located. Equal probability, approx. log2 (n+1)-1
Code implementation:
Main.m
algorithm ---- binary lookup
Copyright (c) year [email protected] All rights reserved.
#import<Foundation/Foundation.h>
int Main (int argc,const Char * argv[])
{
int array[] = {0, 1, 2, 3, 4, 5, 6, 7 , 8, 9, ten};
int count = sizeof(array)/ sizeof(array[0]);
int target = ten;
int start = 0, end = count- 1, mid =0;
while (Start <= end) {
Mid = (start + end)/2;
if (Array[mid] > target) {
End = mid-1;
} Else if (Array[mid] < target) {
Start = mid +1;
} Else {
break;
}
}
if (Start <= end) {
printf ("[%d]:%d\n", Mid, Array[mid]);
} Else {
printf("not found\n");
}
return 0;
}
iOS algorithm (v) binary find