C Program to Merge two Sorted Array
Write a C Program to Merge the Elements of 2 Sorted Array.
This C Program teach you how to merge the elements of 2 sorted array.
C Programming Code
#include <stdio.h>
void main()
{
int array1[50], array2[50], array3[100], m, n, i, j, k = 0;
printf(“\n Enter size of array Array 1: “);
scanf(“%d”, &m);
printf(“\n Enter sorted elements of array 1: \n”);
for (i = 0; i < m; i++)
{
scanf(“%d”, &array1[i]);
}
printf(“\n Enter size of array 2: “);
scanf(“%d”, &n);
printf(“\n Enter sorted elements of array 2: \n”);
for (i = 0; i < n; i++)
{
scanf(“%d”, &array2[i]);
}
i = 0;
j = 0;
while (i < m && j < n)
{
if (array1[i] < array2[j])
{
array3[k] = array1[i];
i++;
}
else
{
array3[k] = array2[j];
j++;
}
k++;
}
if (i >= m)
{
while (j < n)
{
array3[k] = array2[j];
j++;
k++;
}
}
if (j >= n)
{
while (i < m)
{
array3[k] = array1[i];
i++;
k++;
}
}
printf(“\n After merging: \n”);
for (i = 0; i < m + n; i++)
{
printf(“\n%d”, array3[i]);
}
}
Logic
- Create two arrays of fixed size and define their elements in sorted fashion.
- Take any two variables say i and j for the 0th position of these two arrays.
- Then the elements will be compared one by one using i and j in for loop, and whichever element is smaller than the other, that element will get inserted to final array will move by one, whereas the other array’s track position will remain in that same place.
- Above work will be done till we reach the end of either array. After that, one of the arrays whose elements are still to be added, its elements will get straightaway added to the final array.