程序填空题:折半查找[A]
下面程序中IsIn()函数的功能是用二分(折半)法查找某个元素是否在数组中,如果找到了返回元素在数组中的位置,找不到则返回-1. 请将IsIn()函数中缺失的表达式或者语句补上。
c++
#include <stdio.h>
#define N 15
int IsIn(int x,int *S, int Size){
int Left=0,Right=@@[Size-1](2);
int Mid=(Right+Left)/2;
while (Right>=Left){
if(@@[x==S[Mid]](2)) return Mid;
else if(x<S[Mid]) Right=@@[Mid-1](2);
else Left=@@[Mid+1](2);
Mid=(Right+Left)/2;
}
return -1;
}
int main(){
int S[N]={8,14,18,21,23,27,29,32,34,36,40,43,47,50,56};
int x=40;
if(IsIn(x,S,N)!=-1) printf("%d is in the set S\n",x);
else printf("%d is not in the set S\n",x);
x=37;
if(IsIn(x,S,N)!=-1) printf("%d is in the set S\n",x);
else printf("%d is not in the set S\n",x);
return 0;
}
答案:
第1空:Size-1
第2空:x==S[Mid]
第3空:Mid-1
第4空:Mid+1
c++
#include <stdio.h>
#define N 15
int IsIn(int x,int *S, int Size){
int Left=0,Right=@@[Size-1](2);
int Mid=(Right+Left)/2;
while (Right>=Left){
if(@@[x==S[Mid]](2)) return Mid;
else if(x<S[Mid]) Right=@@[Mid-1](2);
else Left=@@[Mid+1](2);
Mid=(Right+Left)/2;
}
return -1;
}
int main(){
int S[N]={8,14,18,21,23,27,29,32,34,36,40,43,47,50,56};
int x=40;
if(IsIn(x,S,N)!=-1) printf("%d is in the set S\n",x);
else printf("%d is not in the set S\n",x);
x=37;
if(IsIn(x,S,N)!=-1) printf("%d is in the set S\n",x);
else printf("%d is not in the set S\n",x);
return 0;
}
答案:
第1空:Size-1
第2空:x==S[Mid]
第3空:Mid-1
第4空:Mid+1