C语言编程,15个由大到小的数有序排列用折半法查找编程不知道这个程序哪儿错 了,求大神指导

如题所述

第1个回答  2014-04-19
#include <stdio.h>
#define N 15
int main()
{ inti,number,top,bott,mid,loca,a[N],flag=1,sign;
char c;
printf("enter data:\n");
scanf("%d",&a[0]);
i=1;
while(i<N)
{scanf("%d",&a[i]);
if (a[i]>=a[i-1])
i++;
else
printf("enter this data again:\n");
}
printf("\n");
for(i=0;i<N;i++)
printf("%5d",a[i]);
printf("\n");
while(flag)
{printf("input number to look for:");
scanf("%d",&number);
sign=0;
top=0; //top是查找区间的起始位置
bott=N-1; //bott是查找区间的最末位置
if ((number<a[0])||(number>a[N-1])) //要查的数不在查找区间内
loca=-1; // 表示找不到
while ((!sign) && (top<=bott))
{mid=(bott+top)/2;
if (number==a[mid])
{loca=mid;
printf("Has found %d, its position is %d\n",number,loca+1);
sign=1;
}
else if (number<a[mid])
bott=mid-1;
else
top=mid+1;
}
if(!sign||loca==-1)
printf("cannot find %d.\n",number);;
printf("continu or not(Y/N)?");
scanf(" %c",&c);
if (c=='N'||c=='n')
flag=0;
}
return 0;
}
具体你可以对比下,不懂可以hi
第2个回答  2014-04-19
折半查找的难点在于下标的界的检查:
你的while循环写得有很大问题:
正确写法:
i=0;j=15-1;//j初始化应为14
while(i<=j){
t=(i+j)/2;
if(a[m]<k)
i=m+1;
else if(a[m]==k)
return m;
else
j=m-1;

}本回答被提问者和网友采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网