实验六 查找中减治法的程序设计

实验名称

实验六 查找中减治法的程序设计

实验目的

(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)之间;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

写bug如流水

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值