Of all the search algorithms, the binary lookup is the simplest one. The binary lookup requires that the original sequence be sorted, each time as compared to the number in the middle of the sequence, and if less than the middle number, then continue the recursive lookup on the left side of the sequence, if greater than the middle number, then continue the recursive lookup on the right side of the sequence. The lookup fails until the number is found, or until there is only one number in the sequence that is not found. The time complexity of the lookup can be achieved O (LOGN), which should be the quickest way to find an O (1), except for an array by subscript. Sample code uploaded to Https://github.com/chenyufeng1991/BinarySearch.
Using the C language complete implementation is as follows:
Implement a binary lookup
#include <stdio.h>
#include <stdlib.h>
void binarysearch (int *arr, int start, int end , int num);
int main (int argc, const char * argv[])
{
int array[] = {4,5,6,7,8,9};
BinarySearch (Array, 0, 5,);
return 0;
}
void BinarySearch (int *arr, int start, int end, int num)
{
int mid = (start + end)/2;
if (arr[mid] = num)
{
printf ("%d", mid);
return;
}
if (start = = end)
{
printf ("not Found");
return;
}
if (num < Arr[mid])
{
BinarySearch (arr, start, Mid, num);
}
if (num > Arr[mid])
{
BinarySearch (arr, mid + 1, end, num);
}
return;
}