Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Let x and y be two vectors of integers arranged so that the elements are in asce

ID: 3575127 • Letter: L

Question

Let x and y be two vectors of integers arranged so that the elements are in ascending numerical order. You are asked to write a function vector merge (vector p, vector q) So that the call merge(x, y) constructs a new vector out of the data values of x and y, so that the elements of the new vector are the combined elements of vectors p and q. The vector returned by the function should also in ascending numeric order. The function should not disturb the original vectors. You cannot use a sort function on the vector. Note; The two input vectors are not necessarily the same length and one or both o1 x and y could be empty vectors. But... the vector class has a size () member function that returns its size. Write function merge corresponding to the requirements above.

Explanation / Answer

#include <iostream>
#include <vector>
using namespace std;
vector<int> merge(vector<int> p,vector<int> q)
{
   int n=p.size();
   int m=q.size();
   vector<int> c;


   int i=0,j=0;
   while(i<n&&j<m)
   {
       if(p[i]<q[j])
       {
           c.push_back(p[i]);
           i++;
       }
       else
       {
           c.push_back(q[j]);
           j++;
       }
   }
   while(i<n)
   {
       c.push_back(p[i]);
           i++;          
   }
   while(i<m)
   {
       c.push_back(q[j]);
           j++;
   }
   return c;
}