【正确答案】先在索引表I中找出x在主表中的位置区间[1,h],由于索引表按关键字key的顺序排序,所以这里的查找采用二分查找法。然后在主表A中的[1,h]区间中查找元素x,由于主表是无序的,所以这里的查找采用顺序查找法。
实现本题功能的程序代码如下:
typedef struct //定义索引表结构
{
elemtype key; //关键值
int link; //指向主表的位置
} index;
typedef elemtype table[maxSize];
//定义主表,maxSize是已经定义的常量
index I[4]={{14,0},{34,5},{66,10},{85,15}};
table A={8,14,6,9,10,22,34,18,19,31,40,38,54,66,46,71,78,68,80,85};
int search()
{
elemtype x;
int place; //保存索引表中位置
int i,l=0,h=3,m,find=0;
cout<<"输入查找的值: ";
cin>>x;
while(l<=h && find==0) //采用二分查找法
{
m=(1+h)/2;
if(x<I[m].key)
h=m-1;
else if(x>I[m].key)
l=m+1;
else
find=1;
}
if(find)
place=m-1;
else
place=1;
if(place<=2) //找出x在A中的位置区间[l,h]
{
l=I[place].link;
h=I[place+1].key-1;
}
else if(place==3)
{
l=I[place].link;
h=19;
}
else //在索引表中未找到x的正确位置
{
cout<<"A中不存在"<<x<<endl;
return 0;
}
i=1; //在A中的位置区间[1,h]中顺序查找x
while(i<=h && A[i]!=x)
++i;
if(i<=h)
tout<<"位置="<<i<<endl;
else //在主表中未找到x的正确位置
{
cout<<"A中不存在"<<x<<endl;
return 0;
}
return 1;
}
}
【答案解析】