您的位置:首页 > 其它

p48_合并两个已排序数组

2017-06-24 18:21 246 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: