顺序查找、二分(折半)查找和索引查找都是静态查找表,其中二分查找的效率最高。
静态查找表的缺点是当表的插入或删除操作频繁时,为维护表的有序性,需要移动表中很多记录。
这种由移动记录引起的额外时间开销,就会抵消二分查找的优点(二分查找和分块查找只适用于静态查找表)。
若要对动态查找表进行高效率的查找,可以使用树表查找(以二叉树或树作为表的组织形式,称为树表)
1 头文件
#ifndef HEAD_H
#define HEAD_H
#include<iostream>
#include<string.h>
typedef int Keytype; // 关键字項
typedef int otherdata; //其他数据項
typedef struct {
Keytype key;
otherdata otherinfo;
}ElemType;
typedef struct BSTNode{
ElemType data;
struct BSTNode *lchild,*rchild;
}BSTNode,*BSTree;
#endif // HEAD_H
2 实现函数
#include"head.h"
using namespace std;
//二叉排序树的查找
BSTree SearchBST(BSTree T,Keytype key){
if((!T)||key == T->data.key)return T;
else if(key<T->data.key)return SearchBST(T->lchild,key);
else return SearchBST(T->rchild,key);
}
//二叉树的插入
void InsertBST(BSTree &T,ElemType e){
if(!T){
BSTNode* S = new BSTNode;
S->data = e;
S->lchild = NULL;
S->rchild = NULL;
T = S;
}else if(e.key<T->data.key)
InsertBST(T->lchild,e); //将 *S 插入左子树
else if(e.key>T->data.key)
InsertBST(T->rchild,e);
}
//二叉排序树的创建
void CreatBST(BSTree &T){
T = NULL;
ElemType e;
cin>>e.key;
while(e.key != 0){ //end by enter 0 and you can change it
InsertBST(T,e);
cin>>e.key;
}
}