Chandu and his Girlfriend Returns

Chandu bought some unsorted arrays and sorted them (in non-increasing order). Now, he has many-sorted arrays to give to his girlfriend. But, the number of sorted arrays is very large so Chandu decided to merge two sorted arrays into one sorted array. But he is too lazy to do that. So, he asked your help to merge the two sorted arrays into one sorted array (in non-increasing order).

Example:

Input:  n = 4, m = 5, a[n] = {9, 7, 5, 3},b[m] = {8, 6, 4, 2, 0}
Output: 9 8 7 6 5 4 3 2 0 

Approach

C++

#include <bits/stdc++.h>
using namespace std;

void mergeTwoArrays(long long nlong long m,
                    long long a[], long long b[])
{
    vector<long longv;
    long long i = 0j = 0;
    while (i < n && j < m)
    {
        if (a[i] > b[j])
        {
            v.push_back(a[i]);
            i++;
        }
        else
        {
            v.push_back(b[j]);
            j++;
        }
    }
    while (i < n)
    {
        v.push_back(a[i]);
        i++;
    }
    while (j < m)
    {
        v.push_back(b[j]);
        j++;
    }
    for (long long i = 0i < v.size(); i++)
        cout << v[i] << " ";
    cout << "\n";
}
int main()
{

    long long n = 4m = 5;

    long long a[n] = {9753};
    long long b[m] = {86420};

    mergeTwoArrays(nmab);

    return 0;
}


No comments:

Post a Comment