Merging two sorted arrays into a single array in C

Last Updated On Sunday 27th Mar 2022

Merging of Two Arrays in C

C Program for Merge Sort.Learn to merge two sorted arrays into a single array so that the resulting merged array is also in sorted form.

	Array1 = 1 , 3 , 5
Array2 = 2 , 4 , 7 , 9
CombinedArray = 1 , 3 , 5 , 2 , 4 , 7 , 9
	

Let’s assume there are two arrays, p and q, of a certain length. The length of the two arrays can differ.The merged array that will be created from the sorted elements of the preceding two arrays will be called array r.

  • The element at p[i] is compared with the element at q[j]. If p[i] is less than q[j], then p[i] is assigned to array r.Same for q[j] is with n p[i], then q[j] is assigned to array r.
  • If p[i] is equal to q[j], then both the elements are assigned to array r. p[i] is added to r[k].The values of the i and k indices are incremented. q[j] is also added to r[k], and the indices of the q and r arrays are incremented.
	#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]);
}
	
	Enter length of first array:3
Enter 3 elements of the first array in sorted order 
1 2 4
Enter length of second array:4
Enter 4 elements of the second array in sorted order
5 6 7 8
The combined sorted array is:
1
2
4
5
6
7
8