9. Let a and b be two vector<int>. i.e. a and b are two vectors, of possibly dif
ID: 3548986 • Letter: 9
Question
9. Let a and b be two vector<int>. i.e. a and b are two vectors, of possibly different sizes, containing integers.
Further assume that in both a and b the integers are sorted in ascending order.
Write only a function in C ++ and explain it fully please :
vector<int> merge( vector<int> a, vector<int> b)
that will merge the two vectors into one new one and return the merged vector,
By merge we mean that the resulting vector should have all the elements from a and b, and all its elements
should be in ascending order.
For example:
a: 2,4,6,8
b: 1,3,7,10,13
the merge will be: 1,2,3,4,6,7,8,10,13
Do this in two ways. In way 1 you cannot use any sorting function. In way 2 you must.
Explanation / Answer
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
/* SORTING FUNCTION CODE NOT VISIBLE */
vector<int> merge(vector<int> a, vector<int> b)
{
vector<int> merged; // merged vector
// pushing all the elements of vector 'a' into vector 'merged'
while (!a.empty())
{
merged.push_back(a.back());
a.pop_back();
}
// pushing all the elements of vector 'b' into vector 'merged'
while (!b.empty())
{
merged.push_back(b.back());
b.pop_back();
}
// sorting function found in algorithm library of C++
int size = merged.size(); // size of vector 'merged'
sort(merged.begin(), merged.begin()+size);
return merged;
}
/* SORTING FUNCTION CODE VISIBLE */
vector<int> merge(vector<int> a, vector<int> b)
{
vector<int> merged; // merged vector
int i = 0, j = 0; // index variables
// checking and pushing the smaller element into vector 'merged'
while (!a.empty() || !b.empty())
{
// if element of vector 'a' is smaller than or equal to that of 'b'
if (a[i] <= b[j])
{
merged.push_back(a[i]);
i++;
}
else
{
merged.push_back(b[j]);
j++;
}
}
// pushing the remaining elements of vector 'a' into vector 'merged'
while (i < a.size())
{
merged.push_back(a[i]);
i++;
}
// pushing the remaining elements of vector 'b' into vector 'merged'
while (j < b.size())
{
merged.push_back(b[j]);
j++;
}
return merged;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.