#include <iostream>
#include <vector>
#include <algorithm>
// 手写一个merge methods
void printVector(std::vector<int> &v){
for(std::vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
std::cout<< *it<<" ";
}
std::cout<<std::endl;
}
// i
// 1 2 3 0 0 0
// 2 5 6
// j
void test(){
using namespace std;
vector<int> v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(0);
v1.push_back(0);
v1.push_back(0);
vector<int> v2;
v2.push_back(2);
v2.push_back(5);
v2.push_back(6);
int i, j = 0;
// 方法一:最简单的解决方法,合并再排序
for (int i = v1.size() - v2.size(); i < v1.size(); i++)
{
/* code */
v1[i] = v2[j++];
}
sort(v1.begin(), v1.end());
printVector(v1);
v1.clear();
v2.clear();
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v2.push_back(2);
v2.push_back(5);
v2.push_back(6);
// 方法二 开辟一个新的临时数组
vector<int> v3;
v3.resize(v1.size() + v2.size());
// int m, n = 0; 只是对n初始化
int m = 0, n = 0;
for (int i = 0; i < v3.size(); i++)
{
if (m >= v1.size())
{
v3[i] = v2[n++];
}
else if (n >= v2.size())
{
v3[i] = v1[m++];
}
else if (v1[m] < v2[n])
{
v3[i] = v1[m++];
/* code */
}
else{
v3[i] = v2[n++];
}
}
printVector(v3);
// 方法三 直接在原数组进行操作,从后往前存放
v1.clear();
v2.clear();
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v2.push_back(2);
v2.push_back(5);
v2.push_back(6);
n = v2.size() -1;
m = v1.size() -1;
v1.resize(v1.size() + v2.size());
for (int i = v1.size() - 1; i > 0; i--)
{
if (m == 0)
{
v1[i] = v2[n--];
/* code */
}
else if (n == 0)
{
v1[i] = v1[m--];
}
else if (v1[m] > v2[n])
{
v1[i] = v1[m--];
}
else{
v1[i] = v2[n--];
}
}
printVector(v1);
// 方法四 直接使用算法merge
v1.clear();
v2.clear();
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v2.push_back(2);
v2.push_back(5);
v2.push_back(6);
v3.resize(v1.size() + v2.size());
merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
v1.assign(v3.begin(), v3.end());
printVector(v1);
}
int main(void){
test();
return 0;
}
解决两个有序数组合并的四种方法--merge算法--基于Vector容器
最新推荐文章于 2024-07-20 11:45:58 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)