C语言二分查找
#include<stdio.h>intBinarysearch(intw[],intf,intx){intm,h=0,l=f-1;while(h<=l){m=(l+h)...
#include <stdio.h>
int Binarysearch(int w[],int f,int x){
int m,h=0,l=f-1;
while(h<=l){
m=(l+h)/2;
if(x==w[m]){
return m;
}
else if(x<w[m]){
l=m-1;
}
else if(x>w[m]){
h=m+1;
}
else{
return 0;
}
}
}
int main()
{
int n,i,y,m,c;
char a[1000][23];
char d[23];
int b[1000];
printf("输入要统计的学生个数:");
scanf("%d",&n);
for(i=0;i<n;++i){
printf("\n学生的姓名:");
scanf("%s",a[i]);
getchar();
printf("C语言课程的成绩:");
scanf("%d",&b[i]);
printf("\n");
}
for(i=0;i<n-1;i++){
for(y=0;y<n-i-1;y++){
if(b[y]<b[y+1]){
m=b[y];
b[y]=b[y+1];
b[y+1]=m;
d[23]=a[i][23];
a[i][23]=a[i+1][23];
a[i+1][23]=d[23];
}
}
}
printf("学生姓名和C语言课程的成绩从高到低输出:\n");
for(i=0;i<n;++i){
printf("%s",a[i]);
printf(":");
printf("%d",b[i]);
printf(" ");
}
printf("\n输入要查找的成绩:");
scanf("%d",&c);
if(Binarysearch(b,n,c))
printf("%s %d",a[Binarysearch(b,n,c)],Binarysearch(b,n,c));
}
为什么这个一到二分查找就不执行了呢 展开
int Binarysearch(int w[],int f,int x){
int m,h=0,l=f-1;
while(h<=l){
m=(l+h)/2;
if(x==w[m]){
return m;
}
else if(x<w[m]){
l=m-1;
}
else if(x>w[m]){
h=m+1;
}
else{
return 0;
}
}
}
int main()
{
int n,i,y,m,c;
char a[1000][23];
char d[23];
int b[1000];
printf("输入要统计的学生个数:");
scanf("%d",&n);
for(i=0;i<n;++i){
printf("\n学生的姓名:");
scanf("%s",a[i]);
getchar();
printf("C语言课程的成绩:");
scanf("%d",&b[i]);
printf("\n");
}
for(i=0;i<n-1;i++){
for(y=0;y<n-i-1;y++){
if(b[y]<b[y+1]){
m=b[y];
b[y]=b[y+1];
b[y+1]=m;
d[23]=a[i][23];
a[i][23]=a[i+1][23];
a[i+1][23]=d[23];
}
}
}
printf("学生姓名和C语言课程的成绩从高到低输出:\n");
for(i=0;i<n;++i){
printf("%s",a[i]);
printf(":");
printf("%d",b[i]);
printf(" ");
}
printf("\n输入要查找的成绩:");
scanf("%d",&c);
if(Binarysearch(b,n,c))
printf("%s %d",a[Binarysearch(b,n,c)],Binarysearch(b,n,c));
}
为什么这个一到二分查找就不执行了呢 展开
1个回答
展开全部
#include <stdio.h>
#include <string.h>
int Binarysearch(int w[],int n,int x) {
int m,high = n - 1,low = 0;
while(low <= high) {
m = (low + high)/2;
if(x == w[m]) return m;
else if(x > w[m]) high = m - 1;
else low = m + 1;
}
return -1;
}
int main() {
int i,j,n,t,index,scr;
char name[1000][23],tmp[23];
int score[1000];
printf("输入要统计的学生个数:");
scanf("%d",&n);
for(i = 0;i < n;++i) {
printf("姓名 成绩:");
scanf("%s%d",name[i],&score[i]);
}
for(i = 0;i < n - 1;i++) {
for(j = 0;j < n - i - 1 ;j++) {
if(score[j] < score[j + 1]) {
t = score[j];
score[j] = score[j + 1];
score[j + 1] = t;
strcpy(tmp,name[j]);
strcpy(name[j],name[j + 1]);
strcpy(name[j + 1],tmp);
}
}
}
printf("学生姓名和C语言课程的成绩从高到低输出:\n");
for(i = 0;i < n;++i)
printf("%s\t%d\n",name[i],score[i]);
printf("\n输入要查找的成绩:");
scanf("%d",&scr);
index = Binarysearch(score,n,scr);
if(index >= 0) printf("%s\t%d\n",name[index],score[index]);
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询