用C语言编写非递归算法实现折半查找(二分查找)

用C语言编写非递归算法实现折半查找(二分查找)
2024年11月23日 08:08
有2个网友回答
网友(1):

#include

int* binary_search( int* a, int* b, int n )
{
int* m;
while ( b > a ) {
m = a + ( b - a ) / 2;
if ( *m < n )
a = m + 1;
else if ( *m > n )
b = m;
else
return m;
}
return NULL;
}

int main()
{
int a[] = { 1,3,5,7,9,11,13,15,17,19 };
int* p1, *p2;
p1 = binary_search( a, a + 10, 9 );
p2 = binary_search( a, a + 10, 8 );
if ( p1 ) {
printf( "find %d at pos:%d\n", 9, p1 - a );
}
if ( !p2 ) {
printf( "can't find value %d\n", 8 );
}
return 0;
}

网友(2):

int i1,i2,i3,num[10]; int a;//要找的数i1=0;i3=9;while(i1<=i3){
i2=(i1+i3)/2;if(a==num[i2]){
printf("要找的数字是第%d个成员\n",i2);return;} else if(ai3=i2-1;else
i1=i2+1; }printf("数组中没有你要找的数字\n");