C Program to merge two sorted arrays into single array

In this c programming example we will write a program to merge two sorted arrays into single array.

  • Let's take two arrays A and B with a certain length. This length can be differ.
  • Take other array C which will store the elements which are soreted from the above arrays A and B Now the logic will be go like
  • The element in A at A[i] is compared with the element at array B[j]. If the element A[i] is less than B[j] then the element at A[i] is assigned to array C, then the indices of the Array A and B will be increases

C[k]=A[i];

i++;

k++;

  • If the B[j] is less than A[i] then B[j] will assigned to C so

C[k]=B[j];

i++;

k++;

  • If the both A[i] and B[j] equal then both elements would be added to Array C

C[k]=A[i];

i++;

k++;

C[k]=B[j];

i++;

k++;

  • This steps will repeated until any of the array elements could be over

 

 

#include<stdio.h>
#define max 100
void main()
{
int p[max], q[max], r[max];
 int m,n;
 int i,j,k;
 printf("Enter length of first array:");
 scanf("%d",&m);
 printf("Enter %d elements of the first array in sorted order \n",m);
 for(i=0;i<m;i++)
 scanf("%d",&p[i]);
 printf("\nEnter length of second array:");
 scanf("%d",&n);
 printf("Enter %d elements of the second array in sorted order\n",n);
 for(i=0;i<n;i++ )
 scanf("%d",&q[i]);
 i=j=k=0;
 while ((i<m) && (j <n))
 {
    if(p[i] < q[j])
    {
       r[k]=p[i];
       i++;
       k++;
    }
    else
    {
       if(q[j]< p[i])
       {
          r[k]=q[j];
          k++;
          j++;
       }
       else
       {
          r[k]=p[i];
          k++;
          i++;
          r[k]=q[j];
          k++;
          j++;
       }
    }
 }
 while(i<m)
 {
    r[k]=p[i];
    k++;
    i++;
 }
 while(j<n)
 {
    r[k]=q[j];
    k++;
    j++;
 }
 printf("\nThe combined sorted array is:\n");
 for(i = 0;i<k;i++)
 printf("%d\n",r[i]);
}

 

Output:

Enter length of first array:5
Enter 5 elements of the first array in sorted order
1
3
5
7
9

Enter length of second array:4
Enter 4 elements of the second array in sorted order
2
4
6
8

The combined sorted array is:
1
2
3
4
5
6
7
8
9