给一个严格递增数列,函数int Search_Bin(SSTable T, KeyType k)用来二分地查找k在数列中的位置。
函数接口定义:
int Search_Bin(SSTable T, KeyType k)
裁判测试程序样例:
#include
using namespace std;
#define MAXSIZE 50
typedef int KeyType;
typedef struct
{ KeyType key;
} ElemType;
typedef struct
{ ElemType *R;
int length;
} SSTable;
void Create(SSTable &T)
{ int i;
T.R=new ElemType[MAXSIZE+1];
cin>>T.length;
for(i=1;i<=T.length;i++)
cin>>T.R[i].key;
}
int Search_Bin(SSTable T, KeyType k);
int main ()
{ SSTable T; KeyType k;
Create(T);
cin>>k;
int pos=Search_Bin(T,k);
if(pos==0) cout<<"NOT FOUND"<else cout<return 0;
}
/* 请在这里填写答案 */
int Search_Bin(SSTable T,KeyType k){
KeyType l,r,med;
l=1;
r=T.length;
while(l<=r){
med=(l+r)/2;
if(T.R[med].key==k) return med;
else if(T.R[med].key>k) r=med-1;
else l=med+1;
}
return 0;
}
int Search_Bin(SSTable T,KeyType k){
KeyType l,r,med;
l=1;
r=T.length;
while(l<=r){
med=(l+r+1)/2;
if(T.R[med].key==k) return med;
**else if(T.R[med].key>k) r=med;
else l=med;**
}
return 0;
}
pta会提示:
如果不加一减一改变边界,程序会死循环的,你可以弄一组数据跟着代码试试,这样百分百超市