Wednesday, 22 February 2017

C Program to Merge two sorted Arrays in non-increasing order

This question has been already appeared in the interviews of following companies:
Juniper, Synopsis, Snapdeal, Brocade, Amdocs, Goldman Sachs, Quickr, Microsoft, Linkedin, Zoho
 

In the question you have given two sorted array and then you have to merge them into single sorted array in non-increasing order.

Source :- geeksforgeeks  

We strongly recommend you to try this program on geeksforgeeks before seeing the solution.

Input:-

In inputs, First line contains T, which is denoting the number of test cases.
First line of each test case contains two space separated integers X and Y, denoting the size of the two sorted arrays.
Second line of each test case contains X space separated integers, denoting the first sorted array P.
Third line of each test case contains Y space separated integers, denoting the second array Q.


Ouput:-

For each test case, print (X + Y) space separated integer representing the merged array.

Constraints:- 

1<T<=100
1<=X,Y<=50000
0<=Xi,Yi<=10^9 





#include <stdio.h>
#define MAX 50000
void merge(int n1,int n2);
int arr1[MAX],arr2[MAX];
int main() {
    
    int n1,n2,i,j,t;    /*t is the number of test cases */
    scanf("%d",&t);
    for(i=0;i<t;i++)
    {
          scanf("%d%d",&n1,&n2);   /*n1 & n2 are the number of elements in array1 and array2 */
          for(j=0;j<n1;j++)
          {
              scanf("%d",&arr1[j]);
          }
          for(j=0;j<n2;j++)
          {
              scanf("%d",&arr2[j]);
          }
          merge(n1,n2);
    }
    return 0;
}
void merge(int n1,int n2) /*here we are calling to method merge to merging both arrays in sorted order */
{
    int n,i=0,j=0,k=0,arr3[n1+n2];
    while(j<n1 && k<n2)
    {
          if(arr1[j]>arr2[k])
          {
               arr3[i]=arr1[j];
               i++;
               j++;
          }
          else
          {
               arr3[i]=arr2[k];
               i++;
               k++;
          }
    }
    if(j>=n1)
    {
        while(k<n2)
        {
            arr3[i]=arr2[k];
            i++;
            k++;
        }
    }
    else
    {
        while(j<n1)
        {
            arr3[i]=arr1[j];
            i++;
            j++;
        }
    }
    n=n1+n2;
    for(i=0;i<n;i++)
    {
        printf("%d ",arr3[i]);
    }
    printf("\n");
}


OUTPUT:


See also: - Algorithm Implementation of merging two sorted array in C in increasing Order

2 comments

This comment has been removed by a blog administrator.

Wonderful blog & good post.Its really helpful for me, awaiting for more new post. Keep Blogging!
Web Design Training


EmoticonEmoticon