查找

数据结构编程练习(七)

<1>

有序表的简单顺序查找。

2 有序表的二分查找

3 有序表的递归二分查找。

<2>

1 二叉排序树及其查找

<1>代码实现:

#include "iostream"
using namespace std;
struct entry
{
	int key;
};
//简单顺序查找
int seq_search(entry A[],int n,int x)
{
	int i=n;
	A[0].key=x;//监视哨 
	while(A[i].key!=x)
	    i--;
	return i;
} 
//有序表的二分查找
int bin_search(entry A[],int n,int x)
{
	int mid,low=1,high=n;
	while(low<=high)
	{
		mid=(low+high)/2;
		if(x==A[mid].key)
		    return mid;
		else if(x<A[mid].key)
		    high=mid-1;
		else
		    low=mid+1;
	}
	return 0;
} 
//递归实现顺序表的二分查找
int dbin_search(entry A[],int low,int high,int x)
{
	int mid;
	if(low>high)
	    return 0;
	else
	{
		mid=(low+high)/2;
		if(x==A[mid].key)
		    return mid;
		else if(x<A[mid].key)
		    return dbin_search(A,low,high,x);
	}
} 
int main()
{
	int n,x,i=1;
	entry A[100];
	cout<<"请输入顺序表,以负数作为结束标志:"; 
	while(cin>>n&&n>=0)
	{
		A[i].key=n;
		i++;
	}
	cout<<"所要查找的数为(若不存在,输出为0):";
	cin>>x;
	cout<<"简单顺序查找的位置为:";
	cout<<seq_search(A,i,x)<<endl;
    cout<<"二分查找的位置为:";
	cout<<bin_search(A,i,x)<<endl; 
	int low=1,high=i;
	cout<<"递归二分查找的位置为:";
	cout<<dbin_search(A,low,high,x)<<endl; 	
	return 0;
} 
<2> 代码实现:
#include "iostream"
using namespace std;
struct bnode
{
	int data;
	bnode *lchild,*rchild;
};
//插入新结点到二叉排序树 
void insert(bnode *&T,bnode *u)
{
	if(T==NULL)
		T=u;	    
	else if(u->data<T->data)
		insert(T->lchild,u);
	else
		insert(T->rchild,u);     
}
//二叉排序树的构造 
void create_bst(bnode *&T) 
{
	bnode *u;
	int x,i=0;
	T=NULL;
	cin>>x;
	while(x>=0)
	{
		i++;
		u=new bnode;
		u->data=x;
		u->lchild=NULL;
		u->rchild=NULL;
		insert(T,u);
		cin>>x;
	}
}
//递归查找二叉排序树
bnode *bst_search(bnode *T,int x)
{
	if(T==NULL||T->data==x)
	    return T;
	else if(x<T->data)
	    return bst_search(T->lchild,x);
	else
	    return bst_search(T->rchild,x);
} 
//非递归查找二叉排序树
bnode *dbst_search(bnode *T,int x)
{
	bnode *p=T;
	while(p!=NULL)
	{
		if(x==p->data)
		    return p;
		else if(x<p->data)
		    p=p->lchild;
		else
		    p=p->rchild;
	}
	return p;
} 
int main()
{
	bnode *T;
	int x;
	cout<<"请输入排序树中的数,以负数作为结束标志:";
	create_bst(T);
	cout<<"请输入要查找的数:";
	cin>>x;
	cout<<"递归查找的位置是:"<<bst_search(T,x)<<endl;
	cout<<"非递归查找的位置为:"<<dbst_search(T,x)<<endl; 
	return 0;
} 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值