用c语言二分法查表法查找数是否在序列中
使用二分法查表法,查找从键盘输入的任意一个数,是否在下面的数据序列中。91625322129813621...
使用二分法查表法,查找从键盘输入的任意一个数,是否在下面的数据序列中。
9 16 25 32 2 1 29 81 36 21 展开
9 16 25 32 2 1 29 81 36 21 展开
3个回答
展开全部
#include<stdio.h>
void main()
{ int a[10]={9,16,25,32,2,1,29,81,36,21};
int key,low=0,high=10-1,mid,k=-1;
int i,j,t;
printf(" please input:");
scanf("%d",&key);
for(i=0;i<10;i++)
{for(j=0;j<10-i;j++)
if(a[j]>a[j+1])
{t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
while(low<=high)
{mid=(low+high)/2;
if(a[mid]==key)
{k=mid;
break;
}
else if(a[mid]<key)
low=mid+1;
else high=mid-1;
}
if(k==-1)
printf(" no find");
else
printf("yes");
printf("\n");
}
void main()
{ int a[10]={9,16,25,32,2,1,29,81,36,21};
int key,low=0,high=10-1,mid,k=-1;
int i,j,t;
printf(" please input:");
scanf("%d",&key);
for(i=0;i<10;i++)
{for(j=0;j<10-i;j++)
if(a[j]>a[j+1])
{t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
while(low<=high)
{mid=(low+high)/2;
if(a[mid]==key)
{k=mid;
break;
}
else if(a[mid]<key)
low=mid+1;
else high=mid-1;
}
if(k==-1)
printf(" no find");
else
printf("yes");
printf("\n");
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
#include <stdio.h>
#define N 8
main()
{
int i,low,high,mid,find;
int a[N],x;
printf("please input 8 numbers:\n");
for(i=0;i<N;i++)
scanf("%d",&a[i]);
printf("please input an integer to look for:\n");
scanf("%d",&x);
low=0;
high=N-1;
find=0; //找到要查找的数时,find=1;
while (low<high && find==0)
{
mid=(low+high)/2;
if(x==a[mid])
{
printf("%d is found ,it is a[%d]\n",x,mid);
find=1;
break;
}
else if(x<a[mid])
high=mid-1;
else
low=mid+1;
}
if(find==0)
printf("%d is not in array\n",x);
}
#define N 8
main()
{
int i,low,high,mid,find;
int a[N],x;
printf("please input 8 numbers:\n");
for(i=0;i<N;i++)
scanf("%d",&a[i]);
printf("please input an integer to look for:\n");
scanf("%d",&x);
low=0;
high=N-1;
find=0; //找到要查找的数时,find=1;
while (low<high && find==0)
{
mid=(low+high)/2;
if(x==a[mid])
{
printf("%d is found ,it is a[%d]\n",x,mid);
find=1;
break;
}
else if(x<a[mid])
high=mid-1;
else
low=mid+1;
}
if(find==0)
printf("%d is not in array\n",x);
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
二分法查找的值是要先排好序的
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询