实验名称
实验六 查找中减治法的程序设计
实验目的
(1)掌握减治法的设计思想;
(2)掌握折半查找和二叉查找的思想及实现过程;
(3)在掌握的基础上编程实现两种查找方法的具体实现过程。
实验题目
给出一个序列及要查找的值,分别用两种查找方法实现,输出结果,输出时要求有文字说明。请任选一种语言编写程序实现上述算法,并分析其算法复杂度。
实验源代码
折半查找:
#include <stdio.h>
int BinSearch(int a[],int n,int key)
{
int low,high,mid,count1=0,count2=0;
low=0;
high=n-1;
while(low<=high)
{
count1++;
mid=(low+high)/2;
if(key<a[mid])
high=mid-1;
else if(key>a[mid])
low=mid+1;
else if(key==a[mid])
{
printf("查找成功!\n 查找 %d 次!a[%d]=%d",count1,mid,key);
count2++;
break;
}
}
if(count2==0)
printf("查找失败!");
return 0;
}
int main()
{
int i,key,a[100],n;
printf("请输入数组的长度:\n");
scanf("%d",&n);
printf("请输入数组元素:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("请输入你想查找的元素:\n");
scanf("%d",&key);
BinSearch(a,n,key);
printf("\n");
return 0;
}
二叉查找树:
#include <stdio.h>
#include "stdlib.h"
struct BiNode{
int data;
BiNode * lchild, * rchild;
};
BiNode * SearchBST(BiNode * root, int k){
if (root == NULL) return NULL;
else if (root->data == k) return root;
else if (k<root->data)
return SearchBST(root->lchild, k);
else
return SearchBST(root->rchild, k);
}
BiNode * InsertBST(BiNode * root, int data) {
if (root == NULL){
root = new BiNode;
root->data = data;
root->lchild = root->rchild = NULL;
return root;
}
if (data<=root->data)
root->lchild = InsertBST(root->lchild, data);
else
root->rchild = InsertBST(root->rchild, data);
return root;
}
BiNode * createBST(int a[], int n){
BiNode * T = NULL;
for (int i=0; i<n; i++)
T = InsertBST(T, a[i]);
return T;
}
int main() {
BiNode *T = NULL;
int a[100];
int n,key;
printf("请输入数组长度:\n");
scanf("%d", &n);
printf("请输入数值元素:\n");
for(int i=0; i<n; i++){
scanf("%d",&a[i]);
}
T = createBST(a,n);
printf("请输入要查找的数:\n");
scanf("%d",&key);
if(SearchBST(T,key))
printf("查找成功!");
else printf("查找失败!");
}
实验结果
折半查找:
二叉查找树:
折半查找的时间复杂度:T(n) = O(logn);
二叉查找树的时间复杂度O(logn)和O(n)之间;