Binary search:
a is the array to be searched. The prerequisite for binary search is that the a data is sorted. key is the variable to be searched, and n is the length of array a.
int binary( int *a, int key, int n )
{
int left = 0, right = n - 1, mid = 0;
mid = ( left + right ) / 2;
while( left < right && a[mid] != key )
{
if( a[mid] < key )
left = mid + 1;
key ) else if( a[mid] > key ) right = mid - 1;
mid = ( left + right ) / 2;
}
if( a[mid] == key ) return mid;
return -1;
}
{
int a[] = {1,2,3,4,5,6,7,8,9,12,13,45,67,89,99,101,111,123,134,565,677};
int b[ ] = { 677, 1, 7, 11, 67 };
int i;
for( i=0; i
{
printf( "%dn", binary( a, b[i], sizeof(a)/ sizeof(a[0])));
}
return 0;
}