栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

查找和排序的实现

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

查找和排序的实现

实验目的:
(1)掌握折半查找和二叉排序树两种查找方法;
(2)掌握各种不同的排序方法。

实验内容:
(1)编程实现两种查找方法:折半查找和二叉排序树;
若查找成功,返回元素在有序数组中的位置和查找次数;
若查找失败,返回出错标志和查找次数。
(2)从教材中选择两种排序算法进行编程实现。

实验代码:

#include 
using namespace std;


typedef struct{
	int *R;
	int length;
}STable;

int Init(STable &ST)
{
	ST.R=new int[100];
	if(!ST.R) return 0;
	ST.length=0;
	return 1;
}

int Create(STable &ST)
{
	int n;
	cout<<"输入元素个数:"<>n;
	ST.length=n;
	cout<<"输入元素:"<
		int e;
		cin>>e; 
		ST.R[i]=e;
	}
}
int Search_Bin(STable ST,int key,int &count)
{
	int low=0;
	int high=ST.length-1;
	while(low<=high)
	{
		int mid=(low+high)/2;
		count++;
		if(key==ST.R[mid])  return mid;
		else if (key
	int data;
	struct BSTNode *l,*r;
}BSTNode,*BSTree;
//二叉排序树的创建 
void InsertBST(BSTree &T,int e)
{
	if(!T)
	{
		BSTNode *S=new BSTNode;
		S->data=e;
		S->l=S->r=NULL;
		T=S;
	}
	else if(edata)
	{
		InsertBST(T->l,e);
	}
	else
	{
		InsertBST(T->r,e);
	}
}
void CreateBST(BSTree &T,int n,int a[])
{
	T=NULL;
	for(int i=0;i
		InsertBST(T,a[i]);
	}
 } 

BSTree SearchBST(BSTree &T,int key,int &count)
{
	BSTree q;
	q=T;
	while(q)
	{
		count++;
		if(q->data==key) 
		{
			return q;
			q=NULL;
		}
		else if(q->data>key) 
		{
			q=q->l;	
		}
		else 
		{
			q=q->r;
		}
	}
	return NULL;
}
 
void midTraverse(BSTree &T)
{
	if (T)
	{
		midTraverse(T->l);
		cout<data<<" ";
		midTraverse(T->r);
	}
}




//直接插入排序 
void InsertSort(int a[],int l)
{
    int temp;
    int j;
    for(int i=1;i
        if(a[i]
            temp=a[i];
            for(j=i-1;j>=0&&temp
                a[j+1]=a[j];
            }
            a[j+1]=temp;

        }
       

    }
}
//快速排序 
void QuickSort(int *num,int l,int r){
	if(l+1>=r){
		return ;
	}
	int first=l,last=r-1,key=num[first];
	while(first
		while(first=key){
			--last;
		}
		num[first]=num[last];
		while(first
			++first;
		} 
		num[last]=num[first];
	}
	num[first]=key;
	QuickSort(num,l,first);
	QuickSort(num,first+1,r);
}
int main()
{
	cout<<"二叉排序树:"<>num;
	cout<<"请输入元素:"<
		cin>>arr[i];
	}
	CreateBST(T,num,arr);
	cout<<"中序遍历二叉搜索树结果:"<>key;
	int count=0;
	BSTree result=SearchBST(T,key,count);
	if(result==NULL) 
	{
		cout<<"查找失败,查找次数为:"<
		cout<<"查找成功,查找值为:"<data<<",查找次数为:"<>key2;
	int result2=Search_Bin(ST,key2,count);
	cout<<"count:"<
		cout<<"查找失败,查找次数为:"<
		cout<<"查找成功,查找位置为:"<2,5,8,3,6,9,1,4,7};
	cout<<"原数组:"<2,5,9,3,6,7,4,1,0,8};
    cout<<"原数组:"<
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/980435.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号