1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <iostream>
int binsearch( int A[], int value, int low, int high )
{
if ( low > high ) return -1;
int mid = ( low + high ) / 2;
if ( A[mid] == value ) return mid;
else if ( A[mid] < value ) return binsearch( A, value, mid + 1, high );
else return binsearch( A, value, low , mid - 1 );
}
int main()
{
int A[] = { 1, 2, 3, 5, 8, 11 };
int N = sizeof A / sizeof A[0];
int value = 12;
std::cout << binsearch( A, value, 0, N - 1 );
}
| |