有15个数按由小到大的顺序存放在一个数组中,输入一个数,用折半查找法找出它是数组中的第几个元素的值。如果不在的话,就打印“没有找到”
在我的教材里看到的这个程序,怎么运行时,如果数组里有的数就正确呢? 当数组里没有这个数时运行就不正确了?就不能按照要求显示!这是怎么回事啊?请教下!谢谢各位
#define N 15
void main()
{ int i,num,top,bott,mid,loca,a[N],flag=1,sign=1;
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 the data again:");
}
printf("\n");
for(i=0;i<N;i++)
printf("%4d",a[i]);
printf("\n");
flag=1;
while(flag)
{printf("Input number to look for:");
scanf("%d",&num);
loca=0;
top=0;
bott=N-1;
if((num<a[0])||(num>a[N-1]))
loca=-1;
while((sign==1)&&(top<=bott))
{mid=(top+bott)/2;
if(num==a[mid])
{loca=mid;
printf("Find %d, its position is %d\n",num,loca+1);
sign=0;
}
else if(num<a[mid])
bott=mid-1;
else
top=mid+1;
}
if(sign==1||loca==-1)
printf("%d is not found.\n",num);
printf("Continue or not (Y/N)?");
scanf("%c",&c);
if(c=='N'||c=='n')
flag=0;
}
}