数据结构算法成长笔记(9.16)算法2.7

数据结构(严蔚敏)算法2.7

-----------------------------------------------------------------------------------

Problem:顺序表的合并:两个升序线性表a和b,合并成一个线性表c,时间复杂度为O(La.lenth+Lb.lenth)。

-----------------------------------------------------------------------------------

代码区

#include <iostream>
#include <malloc.h>
using namespace std;
struct List
{
	int * sta;
	int lenth;
	int loclen;
};
void InitList(List* Ls,int lenth);
void InputList(List* Ls);
void SortList(List* Ls);
void ShowList(const List* Ls);
void MergeList(List* a,List* b);
int main()
{
	List la,lb;	
	int alen,blen;
	cout<<"请输入初始化表a,表b的长度"<<endl;
	cin>>alen>>blen;
	cout<<"请初始化表a的数值"<<endl;
	InitList(&la,alen);
	InputList(&la);
	SortList(&la);
	cout<<"请初始化表b的数值"<<endl;
	InitList(&lb,blen);
	InputList(&lb);
	SortList(&lb);
	cout<<"当前表a的数值为:"<<endl;
	ShowList(&la);
	cout<<"当前表b的数值为:"<<endl;
	ShowList(&lb);
	cout<<"当前表c的数值为:"<<endl;
	MergeList(&la,&lb);
	return 0;
}
void InitList(List* Ls,int lenth)
{
	Ls->sta=(int *)malloc(sizeof(int)*lenth);
	if(!Ls->sta) 
	{
		cout<<"内存分配失败!!!"<<endl;
		exit;
	}
	Ls->loclen=0;
	Ls->lenth=lenth;	
}
void InputList(List* Ls)
{
	cout<<"请输入表中元素"<<endl;
	for(int i=0;i<Ls->lenth;i++)
		cin>>Ls->sta[i];
	Ls->loclen=Ls->lenth;
}
void SortList(List* Ls)
{
	int i,j;
	for(i=0;i<Ls->lenth-1;i++)
		for(j=i+1;j<Ls->lenth;j++)
		{
			if(Ls->sta[i]>Ls->sta[j])
			{
				int temp=Ls->sta[i];
				Ls->sta[i]=Ls->sta[j];
				Ls->sta[j]=temp;
			}
		}
}
void ShowList(const List* Ls)
{
	int*p=Ls->sta,*pe=&Ls->sta[Ls->loclen-1],i=0;
	for(p;p<=pe;p++,i++)
		cout<<*p<<" ";
	cout<<endl;
}
void MergeList(List* a,List* b)
{
	int* p1=a->sta,*p2=b->sta;
	int Lenth_C=a->lenth+b->lenth;
	List c,*LC=&c;
	InitList(LC,Lenth_C);
	int*p1end=&a->sta[a->lenth-1];
	int*p2end=&b->sta[b->lenth-1];
	while(p1<=p1end&&p2<=p2end)
	{
		if(*p1<*p2)
			LC->sta[LC->loclen]=*p1++;
		else
			LC->sta[LC->loclen]=*p2++;	
		LC->loclen++;
	}
	while(p1<=p1end)
	{
		LC->sta[LC->loclen]=*p1++;
		LC->loclen++;
	}
	while(p2<=p2end)
	{
		LC->sta[LC->loclen]=*p2++;
		LC->loclen++;
	}
	int*p=LC->sta,*pe=&LC->sta[LC->loclen-1],i=0;
	for(p;p<=pe;p++,i++)
		cout<<*p<<" ";
	cout<<endl;
}

结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值