C program to merge two arrays Data Structure Tutorial

Updated:01/02/2024 by Computer Hope

Go Back

The list can be defined as an abstract data type in which the elements are stored in an ordered manner for easier and efficient retrieval of the elements.

In C, merging two sorted arrays into a single sorted array is known as merging two sorted arrays. Comparing each array's first element and appending the smaller one to a new array is an effective way to accomplish this. Until every element from both arrays is added to the new array, the process is repeated. Here's an illustration:


First Array = [2,5,10,100,112]
Second Array = [2,15,20,35,60,65,90]

          //Linear Merge
#include<stdio.h>
#include<conio.h>
void main()
{
  int x[5]={2,5,10,100,112};
  int y[7]={2,15,20,35,60,65,90};
  int z[12],i=0,j=0,k=0;
  clrscr();
  while(i<5&&j<7)
  {
	 if(x[i]<y[j])
		z[k++]=x[i++];
	 else
		z[k++]=y[j++];
  }
  if(i<5)
  {
	 while(i<5)
		z[k++]=x[i++];
  }
  else
  {
	 while(j<7)
		z[k++]=y[j++];
  }
  printf("\nmearged array is:");
  for(k=0;k<12 ;k++)
	 printf("  %d",z[k]);
  getch();
}
        

Conclusion

To merge any two arrays in C programming, start adding each and every element of the first array to the third array (the target array). Then start appending each and every element of the second array to the third array (the target array), as shown in the program given below.