用C语言编写非递归算法实现折半查找(二分查找)
答案:2 悬赏:10 手机版
解决时间 2021-04-22 00:41
- 提问者网友:喧嚣尘世
- 2021-04-21 11:06
用C语言编写非递归算法实现折半查找(二分查找)
最佳答案
- 五星知识达人网友:动情书生
- 2021-04-21 12:12
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(a<num[i2])
i3=i2-1;else
i1=i2+1; }printf("数组中没有你要找的数字\n");
i2=(i1+i3)/2;if(a==num[i2]){
printf("要找的数字是第%d个成员\n",i2);return;} else if(a<num[i2])
i3=i2-1;else
i1=i2+1; }printf("数组中没有你要找的数字\n");
全部回答
- 1楼网友:妄饮晩冬酒
- 2021-04-21 13:02
#include <stdio.h>
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;
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯