实现折半查找与遍历二叉排序树
一、实验目的
- 掌握几种典型的查找方法(折半查找、二叉排序树的查找、哈希查找)。
- 对各种查找算法的特点、使用范围和效率有进一步的了解。
- 了解图的典型应用的算法程序。
二、实验内容:
- 编程实现折半查找。
- 读入一串整数构成一棵二叉排序树,对该排序二叉树进行中序遍历,输出其结果。
- 用除留余数法构造哈希函数,并用线性探测再散列处理冲突,实现哈希表的基本操作,即表的构造和查找。
三、实验要求
1.前两个题目必做,第3题选做。
2.在本题下面提交源程序和实验运行结果截图。
3.上交纸质实验报告和电子版实验报告(由学习委员统一收齐上交)。
1. 编程实现折半查找。
#include<iostream>
using namespace std;
typedef struct{
int data;
int otherwise;
}elemtype;
typedef struct{
elemtype a[20];
int length;
}sstable;
int search_bin(sstable s,int n)
{
int low=1,high=s.length,m;
while(low<=high)
{
m=(low+high)/2;
if(s.a[m].data==n)return m; //找到,输出所在位置
else
if(s.a[m].data<n)low=m+1; //继续在小于的表中查询
else
high=m-1; //继续在大于的表中查询
}
return 0;
}
int main()
{
sstable s;
int i,n,k=67;
printf("输入线性表的长度:\n");
cin>>s.length;
printf("输入递增数列:\n");
for(i=0;i<s.length;i++)
cin>>s.a[i].data;
printf("折半查询所得到的位置:%d\n",search_bin(s,k)+1);
}
四、实验结果
2. 读入一串整数构成一棵二叉排序树,对该排序二叉树进行中序遍历,输出其结果。
#include<iostream>
using namespace std;
int i,j,k,e,n;
typedef struct {
int key;
int otherwise;
} elemtype;
typedef struct bstnode {
elemtype data;
int length;
struct bstnode *lchild,*rchild;
} bstnode,*bstree;
void insertbstnode(bstree &T,int e) {
if(!T) {
bstree s;
s=new bstnode;
s->data.key=e;
s->lchild=s->rchild=NULL;
T=s; //将插入的点链接到已找到的插入位置
} else if(e<T->data.key) //小于当前结点的话,按照其左孩子寻找
insertbstnode(T->lchild,e);
else if(e>T->data.key) //大于当前结点的话,按照其右孩子寻找
insertbstnode(T->rchild,e);
}
void creatbstnode(bstree &T) {
T=NULL; //注意这个地方T要为空 ,建立根节点
for(i=0; i<n; i++) {
cin>>e;
insertbstnode(T,e);
}
}
void printfbstree(bstree T) {
if(T) {
printfbstree(T->lchild);
printf("%d ",T->data.key);
printfbstree(T->rchild);
}
}
int main() {
bstree T;
printf("请输入数的数量:\n");
cin>>n;
printf("请输入数字:\n");
creatbstnode(T);
printf("二叉排序树排序后:\n");
printfbstree(T);
}
四、实验结果