学完C语言有好长时间了,我觉得应该把C中一些常用的函数总结一下,这即是对知识的恐固,也能在其中发现自己的不足.
以下代码实现二分法查找功能:
#include
#define SIZE 30
int binarySearch( const int [], int, int, int );
void main()
{
int a[ SIZE ], i, key, result;
for ( i = 0; i <= SIZE - 1; i++ )
a[ i ] = 2 * i+1;
printf( "请输入1个自然数: " );
scanf( "%d", &key );
result = binarySearch( a, key, 0, SIZE - 1 );
if ( result != -1 )
printf( "\n 关键字 %d 位于元素 %d\n", key, result );
else
printf( "\n 没有找到关键字%d\n", key );
}
int binarySearch( const int b[], int searchKey, int low, int high )
{
int middle;
while ( low <= high )
{
middle = ( low + high ) / 2;
if ( searchKey == b[ middle ] )
return middle;
else if ( searchKey < b[ middle ] )
high = middle - 1;
else
low = middle + 1;
}
return -1;
}
阅读(2971) | 评论(0) | 转发(0) |