Merging two sorted arrays in C Programming
Merging arrays once they are sorted is a regular activity to a programmer. Different elements in an array may require sorting before merging especially in C and here is how to handle such. Start by creating the arrays and specify the elements that shall occupy the given arrays. Assuming you have arrays A and B in this case, with already defined sorting nature that may be desired for use.
Now that the definite position of two elements on both arrays is already given, let them occupy the 0th position on both A and B. A comparison will then be done in reference to the two elements using a “for” loop and a final sorted array created after the comparison.
The process of merging when it comes to programming can perfectly be achieved by breaking down element, comparing the elements against each other before forming a final array. The final output should contain both the elements in the two arrays, in this case, A and B.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],b[20],c[40],i,j,k,m,n;
clrscr();
printf("enter how many value in A List\n");
scanf("%d",&m);
printf("Enter %d value in sorted order \n",m);
for(i=0;i<m;i++)
scanf("%d",&a[i]);
printf("enter how many value in B List\n");
scanf("%d",&n);
printf("Enter %d value in sorted order \n",n);
for(i=0;i<n;i++)
scanf("%d",&b[i]);
/* Merge sort logic */
i=j=k=0;
/* Compare A and B List */
while(i<m&&j<n)
if(a[i]>=b[j])
c[k++]= b[j++];
else
c[k++]=a[i++];
/* Remaining Element of A List */
while(i<m)
c[k++]=a[i++];
/* Remaining Element of b List */
while(j<n)
c[k++]= b[j++];
printf("\nA list is :\n");
for(i=0;i<m;i++)
printf("%5d",a[i]);
printf("\nB list is :\n");
for(i=0;i<n;i++)
printf("%5d",b[i]);
printf("\nC list is :\n");
for(i=0;i<m+n;i++)
printf("%5d",c[i]);
getch();
}