#include<stdio.h>
#define N 15
void main()
{
int a[N];
int i,num,top,bott,mid,loca,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 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",&num);
sign=0;
top=0;
bott=N-1;
if((num<a[0])||(num>a[N-1]))
loca=-1;
while((!sign)&&(top<=bott))
{mid=(top+bott)/2;
if(num==a[mid])
{loca=mid;
printf("has found %d ,its position is %d\n",num,loca+1);
sign=1;
}
else if(num<a[mid])
bott=mid-1;
else
top=mid+1;
}
if(!sign||loca==-1)
printf("can't find %d.\n",num);
printf("continue or not(Y/N)?\n");
scanf("%c",&c);
if(c=='N'||c=='n')
flag=0;
}
}
结果是:
enter data:
1 3 2
enter again:
4 5 6 8 12 23 34 44 45 56 57 58 68
1 3 4 5 6 8 12 23 34 44 45 56 57 58 68
input number to look for:7
can't find 7.
continue or not(Y/N)?
input number to look for:12
has found 12 ,its position is 7
continue or not(Y/N)?
input number to look for:y
has found 12 ,its position is 7
continue or not(Y/N)?
input number to look for:n
has found 12 ,its position is 7
continue or not(Y/N)?
Press any key to continue