p48_合并两个已排序数组

p48_合并两个已排序数组

//相关题目:p48
//给定两个排好序的数组A1和A2,A1的末尾有足够的内存容纳A2的元素。
//请实现一个函数,把A2中的数据插入到A1中去,并且要求所有的元素都是排序的。

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

class Solution
{
public:
	void MergeA1A2(int A1[], int szA1, int A2[], int szA2) 
	{
		if(szA2==0)  //szA1是A1实际数组长度,szA2是A2实际数组长度
			return;
		int p=szA1+szA2-1;
		int p1=szA1-1;
		int p2=szA2-1;
		cout<<p1<<","<<p2<<endl;
		while(p1>=0 && p2>=0)
		{
			if(A1[p1] >= A2[p2])
			{
				A1[p--]=A1[p1];
				--p1;
			}
			else
			{
				A1[p--]=A2[p2];
				--p2;
			}
		}
		if(p1<0)
		{
			while(p2>=0)
				A1[p--]=A2[p2--];
		}
		else
		{
			while(p1>=0)
				A1[p--]=A1[p1--];
		}
	}
};

int main(void)
{
	const int SIZE=20;
	int A1[SIZE]={2,4,6,10}; //4
	int A2[]={1,3,5,6,7,8,9,11};  //8

	//int A1[SIZE]={2,4,6,10}; //4
	//int A2[10]={};  //0

	//int A1[SIZE]={}; //0
	//int A2[]={1,3,5,6,7,8,9,11};  //8

	//int A1[SIZE]={}; //0
	//int A2[10]={};  //0

	int szA1=4;
	int szA2=8;
	Solution object;
	object.MergeA1A2(A1,szA1,A2,szA2);
	for(auto mem:A1)
		cout<<mem<<" ";
	cout<<endl;

	system("pause");
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值