不知道为什么有一部总被程序忽略,是关于折半法查找的
有15个数按有小到大顺序存放在一个数组中,输入一个数,要求用折半法查找出这个数是该数组中的第几个元素的值。如果该数不在数组中,则输出"无此数"。(最后加下划线的几句代码总被忽略)
#include<stdio.h>
#define N 15
int main()
{
int i,head,tail,mid,a[N],flag=1,sign,number;
char c;
printf("Please 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("Please enter this data again:\n");
}
printf("The array is:\n");
for(i=0;i<N;i++)
printf("%3d",a[i]);
printf("\n");
while(flag)
{
printf("Please enter the number wanted:");
scanf("%d",&number);
head=0;
tail=N-1;
sign=0;
if((number<a[0])||(number>a[N-1]))
printf("The number can't be found.");
else
{
while((!sign)&&(head<=tail))
{
mid=(head+tail)/2;
if(number==a[mid])
{
printf("The number--%d has been found,it's position is %d.",number,mid+1);
sign=1;
}
else if(number<a[mid])
tail=mid-1;
else if(number>a[mid])
head=mid+1;
}
if(sign==0)
printf("The number can't be found.");
}
printf("\n");
printf("continue or not(Y/N)?");
scanf("%c",&c);
if(c=='N'||c=='n')
flag=0;
}
printf("\n");
return 0;
}