C Program to Merge Two Sorted Arrays

In this post, we will learn to merge two sorted arrays into a single array so that the resulting merged array is also in sorted form.

C Program to Merge Two Sorted Arrays

#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 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 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 first array in sorted order 
10
20
30
40
50

Enter length of second array:6
Enter 6 elements of second array in sorted order
30
40
0 50
60
70
80

The combined sorted array is:
10
20
30
30
40
40
50
50
60
70
80

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments