Binary lookup (also known as two-point lookup)
A simple understanding is to shape an ordered array, in the search process to find the number of the middle of the array compared to the second loop to find, found the return subscript, can not find return-1.
#include < stdio.h > #include < stdlib.h>//binary lookup function int binary_search (int arr[], int key, int line)//determined array length required
To pass to the function as a parameter, the length of the array cannot be computed within the function,//The array parameter is passed as a pointer to {int left = 0;
int right = line-1;
while (left <= right) {int mid = left + (right-left)/2;//Array Intermediate value if (arr[mid] = = key) {
Return mid;//found, returns subscript} else if (Arr[mid] > key) {right = Mid-1;
else {left = mid + 1; } if (Left > right) return-1;//cannot find return-1} int main () {int arr[10] = {2, 4, 6, 8, 10, 12, 14, 1
6, 18, 20}; int key = 100;//number to find int line = sizeof (arr)/sizeof (arr[0);//determine array length int ret = Binary_search (arr, key, line);
Binary lookup function if (ret = 1) {printf ("not found \ n");
else {printf ("Found:%d\n", ret); } System ("PausE ");
return 0; }
Program output results: