返回下标真不优美,因为下标是相对位置,本身并不独立
程序代码:
#include <stdio.h>
int* binary_search( const int a[], size_t n, int key )
{
if( n == 0 )
return NULL;
if( key < a[n/2] )
return binary_search( a, n/2, key );
if( a[n/2] < key )
return binary_search( a+n/2+1, n-n/2-1, key );
return (int*)&a[n/2];
}
size_t findx3( const int a[], size_t n, int key )
{
int* p = binary_search( a, n, key );
if( p )
return p-a;
return -1;
}
#include <assert.h>
int main( void )
{
int a[9];
for( size_t i=0; i!=sizeof(a)/sizeof(*a); ++i )
a[i] = i;
for( size_t i=0; i!=sizeof(a)/sizeof(*a); ++i )
{
size_t index = findx3( a, sizeof(a)/sizeof(*a), a[i] );
assert( index == i );
}
}