1 线性表的查找
数据元素和顺序表的定义
typedef struct{
KeyType key;
InfoType otherinfo;
}ElemType;
typedef struct{
ElemType *R;
int length;
}SSTable;
1.1 顺序查找
int Search_Seq(SSTable ST,KeyType key){
ST.R[0].key=key;
for(int i=ST.length;ST.R[i].key!=key;i--);
return i;
}
ASL分析:
查找成功:
查找失败:
ASL=
1.2 折半查找
int Search_Bin(SSTable ST,KeyType key){
int low=1,high=ST.length;
while(low<=high){
int mid=(low+high)/2;
if(key==ST.R[mid].key) return mid;
else if(key>ST.R[mid].key) low=mid+1;
else high=mid-1;
}
return 0;
}
1.3 分块查找
2 树表的查找
线性表的查找更适用于静态查找表,若要对动态查找进行高效率的查找,可以使用几种特殊的二叉树作为查找表的组织形式,称为树表。
2.1 二叉排序树
数据元素的定义和二叉排序树的二叉链表存储表示
typedef struct{
KeyType key;
InfoType otherinfo;
}ElemType;
typedef struct BSTNode{
ElemType data;
struct BSTNode *lchild,*rchild;
}BSTNode,*BSTree;
二叉排序树的递归查找算法
//二叉排序树的递归查找
BSTree SearchBST(BSTree T,KeyType key){
if(!T||T->data.key==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==NULL){
BSTNode *s=new BSTNode;
s->data=e;
s->lchild=s->rchild=NULL;
T=s;
}else if(e.key<T->data.key){
InsertBST(T->lchild,e);
}else if(e.key>T->data.key){
InsertBST(T->rchild,e);
}
}
创建
//创建排序二叉树
void CreatBST(BSTree &T){
T=NULL;
ElemType e;
cin>>e.key>>e.otherinfo;
while(e.key!=9999){
InsertBST(T,e);
cin>>e.key>>e.otherinfo;
}
}
删除