Wednesday, 22 February 2017

C program for merging two sorted arrays in Increasing Order

C program for merging two sorted arrays into one single sorted array in increasing order is given below

ALGORITHM:

1. n1 is the total number of elements in array1
2. n2 is the total number of elements in array2
3. Declare an empty array3 of size n1+n2
3. set i:=1, j:=1, k:=1
4. do while j<n1 && k<n2
5.         if array1[j] < array2[k]
6.              set:  array3[i]=array1[j]
7.              set:  i=i+1
8.              set:  j=j+1
9.         else
10.             set:  array3[i]=array2[k]
11.             set:  i=i+1
12.             set:  k=k+1
13. EndWhile
14. If j=n1+1
15.      do while k<n2
16.             set:  array3[i]=array2[k]
17.             set:  i=i+1
18.             set:  k=k+1
19. Else:
20.      do while j<n1
21.             set:  array3[i]=array1[j]
22.             set:  i=i+1
23.             set:  j=j+1
23. EndIf
24. set: n=n1+n2


Program:

#include <stdio.h>
#include <stdlib.h>
int merge(int n1,int n2);
int arr1[100],arr2[100],arr3[100];
int main()
{
   int n1,n2,n,i;
   printf("\nEnter the total number of elements of array 1: ");
   scanf("%d",&n1);
   printf("\nEnter the elements of array 1: \n");
   for(i=0;i<n1;i++)
   {
          scanf("%d",&arr1[i]);
   }
   printf("\nEnter the total number of elements of array 2: ");
   scanf("%d",&n2);
   printf("\nEnter the elements of array 2: \n");
   for(i=0;i<n2;i++)
   { 
             scanf("%d",&arr2[i]);
   }
   n=merge(n1,n2);
   printf("\n");
   printf("\nElement of the array after merging are:\n");
   for(i=0;i<n;i++)
   {
        printf("%d ",arr3[i]);
   }
   return 0;
}
int merge(int n1,int n2)
{
   int i,j,k,n;
   i=0;
   j=0;
   k=0;
   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;
   return n;


}


OUTPUT:

 
See also: Program for merging two sorted array into one sorted array in non-increasing order.


EmoticonEmoticon