创建一个索引表
目的
编程实现如下功能:
(1)根据输入索引查找表中的块号和各块中的记录关键字的值创建索引查找表。
(2)利用索引查找确定给定关键字值的记录在索引查找表中的块号和在块中的位置。
核心算法分析
索引查找表有索引表和块表两部分所构成,其中索引表存储的是各块记录中的最大关键字值和各块的起始存储地址,用顺序存储结构,各块的起始存储地址的初始值置为空指针;而块表中存储的是查找表中的所有记录并且按块有序,用链式存储或顺序存储结构,在此用链式存储结构。则索引查找表的存储结构图如7-2所示:
索引表的功能就是快速缩小查找范围,先找到数据所在块,再在块内查找。
代码块(运行环境c++)
下面展示一些 内联代码片
。
#include <iostream>
#define MAXSIZE 100
#define OK 1;
#define OVERFLOW -1;
#include <malloc.h>;
typedef int Status;
typedef int KeyType; //整型关键字类型
typedef struct BNode {
KeyType key; //存储块中记录的关键字值
struct BNode *next; //指向块链中下一记录结点的指针
} BNode,*Bnode2;
//块链中的结点类型
typedef struct SNode {
KeyType Maxkey; //存储各块记录中的最大关键字值
BNode *head; //块链的头指针
} SNode; //索引表中元素的类型
typedef struct {
SNode r[MAXSIZE]; //用于存放索引表中快元素的数组
int length; //用于存放索引表中快的个数
} STable; //索引查找表的结构类型
Status Creat_STable(STable &ST) { //构造一个空的索引表
for(int i=1; i<=MAXSIZE; i++)
ST.r[i].head=NULL;
ST.length=0;
return OK;
}//Creat_SSTable
Bnode2 Init_head(Bnode2 head,int n) { //头插法创建块链
Bnode2 p;
int i=0;
head=(Bnode2)malloc(sizeof(BNode));
head->next=NULL;
while(i<n) {
p=(Bnode2)malloc(sizeof(BNode));
scanf("%d",&p->key);
p->next=head->next;
head->next=p;
i++;
}
return head;
}
int FindBlock(STable ST, KeyType key)
//用二分查找法在索引查找表ST的索引表中确定关键字值为key的待查找记录所在的块号,
//函数并返回值其块号值
{
int low,high,mid;
low=1;
high=ST.length;
while(low<=high) {
mid=(low+high)/2;
if (key==ST.r[mid].Maxkey)
return mid;
else if (key<ST.r[mid].Maxkey)
high=mid-1;
else
low=mid+1;
}
return high+1;
}// FindBlock
int FindRec(STable ST, KeyType key,int &Bno,int &pos)
//用顺序查找法在索引查找表的块链中确定关键字值为key的待查找记录的存储位置
//如果查找成功,记录所在的快号和在快中的位序号分别为Bno和pos,否则都为0
{
BNode *p;
int i=1;
Bno=FindBlock(ST,key); //调用函数,确定待查记录所在块号
printf("在索引表的第%d个位置",Bno);
p=ST.r[Bno].head; //取到待查记录所在块链的头指针
while (p&&p->key!=key) { //顺着链指针依次查找
p=p->next;
i++;
}
if (p) {
pos=i;//查找成功,在快中的位置为i
printf("在块中的位置为%d\n",i-1);
} else
pos=0; //查找不成功,在快中的位置为0
} //FindRec
int MAxBnode(SNode S) { //判断该块中最大的值
int max=0;
S.head=S.head->next;
while(S.head) {
if(S.head->key>max)
max=S.head->key;
S.head=S.head->next;
}
return max;
}
int main() {
STable ST;
Bnode2 T;
Bnode2 p;
int key2;
int get;
int i;
int length;
int pos,Bno;
Creat_STable(ST);
printf("输入索引表的表长:\n");
scanf("%d",&ST.length);
for(i=1; i<=ST.length; i++) {
printf("输入第%d块的长度:",i);
scanf("%d",&length);
printf("请输入第%d块的值:",i);
ST.r[i].head=Init_head(T,length);
ST.r[i].Maxkey=MAxBnode(ST.r[i]);//将第i块中最大的值赋值给Maxkey
}
for(i=1; i<=ST.length; i++) {
printf("第%d块数据最大关键字 ",i);
printf("%d",ST.r[i].Maxkey);
printf("\n第%d块数据 ",i);
p=ST.r[i].head->next; //0号位置未放元素
while(p) {
printf("%d ",p->key);
p=p->next;
}
printf("\n");
}
printf("input KEY\n");
while(1) {
scanf("%d",&key2);
FindRec(ST,key2,Bno,pos);
}
}
运行结果
写代码不易,觉得有帮助就点个赞吧( ̄y▽, ̄)╭