one or two-point searchIn C and C + +, binary lookup is a quick way to find elements for an ordered array.
two or two points to find the conditions and advantages and disadvantagesConditions: For ordered arrays (elements from small to large or from large to minor) advantages: Faster query speed, time complexity of O (n) Disadvantage: There are rigid conditions, and even if found after the insertion and removal difficulties.
third, picture detailed
four or two find C language code block (after encapsulation) Encapsulation Function Interpretation: function prototype: binary_research (int arr[],int left, int right, int element) function: Find the return value of an array element by using the binary: If the element is found, return the element array Otherwise, return-1 code block:
int binary_research (int arr[],int left,int right,int Element)
{while
(left<=right)
{
int mid = ( Left+right)/2;
if (arr[mid]>element)
{right
= mid-1;
}
else if (arr[mid]<element)
{left
= mid + 1;
}
else
{return
mid;
}
}
return-1;
}
Main function code block:
int main ()
{
int array[] = {1,2,3,4,5,6,7,8,9};
int right = <a Target=_blank href= "http://blog.csdn.net/qq_31828515/article/details/51646693" >sizeof (array)/ sizeof (Array[0])-1</a>;//uses <a target=_blank href= "http://blog.csdn.net/qq_31828515/article/details/ 51646693 ">sizeof</a> for array length, 1 for right subscript
int left = 0;//definition right subscript and initialized
to 0 int element = 0;//Define lookup element and initialize to 0
printf ("Please enter the element to find >");
scanf ("%d", &element);
int location = Binary_research (array,left,right,element);
if (location>=0)
printf ("The element ' s location is%d\n", location);
else
printf ("Don ' t exit this element.\n");
return 0;
v. SummaryA binary lookup is faster for an ordered array.
Optimization:You can use int mid = left-(left-right)/2; Prevent Cross-border or
int mid = left&right+ (left^right) >>1;//the computer's favorite bit operation, which is slightly more efficient instead of averaging two numbers
---------------->>> sizeof Print array elements
----------------------->>> Deep preprocessing