Answer to Question #278132 in C++ for zain

Question #278132

Write a program to merge three sorted(ascending) arrays, A1, A2 and A3 and store results back in these arrays. You are required to place results (after sorting) in A3, A2 and A1 in ascending order, i.e., A3 contains smallest set of numbers then A2 and then A3. Take user input for each array of size 5. 


1
Expert's answer
2021-12-11T05:52:12-0500
#include <iostream>
#include <vector>
using namespace std;
using Vector = vector<int>;
void pVector(const Vector& x)
{
    cout << "[";
    for (auto y : x) {
        cout << y << " ";
    }
    cout << "]" << endl;
}
Vector mergeVectors(Vector& A, Vector& B,
                  Vector& C)
{
    int a, b, c, i, j, k;
    a = A.size();
    b = B.size();
    c = C.size();
    Vector R;
    R.reserve(a + b + c);
    i = j = k = 0;
    while (i < a && j < b && k < c) {
        int m = min(min(A[i], B[j]), C[k]);
        R.push_back(a);
        if (a == A[i])
            i++;
        else if (a == B[j])
            j++;
        else
            k++;
    }
    while (i < a && j < b) {
        if (A[i] <= B[j]) {
            R.push_back(A[i]);
            i++;
        }
        else {
            R.push_back(B[j]);
            j++;
        }
    }
    while (i < a && k < c) {
        if (A[i] <= C[k]) {
            R.push_back(A[i]);
            i++;
        }
        else {
            R.push_back(C[k]);
            k++;
        }
    }
    while (j < b && k < c) {
        if (B[j] <= C[k]) {
            R.push_back(B[j]);
            j++;
        }
        else {
            R.push_back(C[k]);
            k++;
        }
    }
    while (k < c)
        R.push_back(C[k++]);
    while (i < a)
        R.push_back(A[i++]);
    while (j < b)
        R.push_back(B[j++]);
    return R;
}
int main()
{
    Vector A = { 1, 2, 41, 52, 84 };
    Vector B = { 1, 2, 41, 52, 67 };
    Vector C = { 1, 2, 41, 52, 67, 85 };
    pVector(mergeVectors(A, B, C));
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog