【C语言】用线性查找与折半查找的两种方法查找成绩-创新互联
从键盘输入某班学生某门课的学号和成绩(假设每班人数不超过40人),当输入为负值时,表示输入结束,试编程从键盘输入一个学号,查找该学号学生的成绩
创新互联公司主营牧野网站建设的网络公司,主营网站建设方案,重庆APP开发公司,牧野h5小程序定制开发搭建,牧野网站营销推广欢迎牧野等地区企业咨询【线性查找】 Linear Search
#include#define N 40
int ReadScore(int score[],long num[]);
int LinSearch(long num[],long x,int n);
int main()
{
int score[N],n,pos;
long num[N],x;
n=ReadScore(score,num);
printf("Total students are %d\n",n);
printf("input the searching ID:");
scanf("%ld",&x);
pos=LinSearch(num,x,n);
if(pos!=-1)
printf("score=%d",score[pos]);
else
printf("Not found!\n");
return 0;
}
int ReadScore(int score[],long num[])
{
int i=-1;
do{
i++;
printf("please input ID and score:");
scanf("%ld%d",&num[i],&score[i]);
}while(num[i]>0&&score[i]>=0);
return i;
}
int LinSearch(long num[],long x,int n)
{
int i;
for(i=0;i
【折半查找】 Binary Search
#include#define N 40
int ReadScore(long num[],int score[]);
int BinSearch(long num[],long x,int n);
int main()
{
int score[N],n,pos;
long num[N],x;
n=ReadScore(num,score);
printf("Total students is %d!\n",n);
printf("input the searching ID:\n");
scanf("%ld",&x);
pos=BinSearch(num,x,n);
if(pos!=-1)
printf("score=%d",score[pos]);
else
printf("Not found!");
return 0;
}
int ReadScore(long num[],int score[])
{
int i=-1;
do{
i++;
printf("please input student is ID and score:\n");
scanf("%ld%d",&num[i],&score[i]);
}while(num[i]>0&&score[i]>=0);
return i;
}
int BinSearch(long num[],long x,int n)
{
int mid,left=0,right=n-1;
while(left<=right)
{
mid=(left+right)/2;
if(x>num[mid])
left=mid+1;
else if(x
提示:mid为输入数组的中间数个数,如果不能整除也没关系,前后两个数都可取
用折半查找效率要高一点
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧
当前名称:【C语言】用线性查找与折半查找的两种方法查找成绩-创新互联
URL链接:http://ybzwz.com/article/phppp.html