C Program to Merge Two Sorted Arrays

C Program to Merge Two Sorted Arrays:
If you are using any software then below program will not give an error, but if you are using TURBO C then you have to make some changes like: void main() and some function like clrscr() or getch().

#include<stdio.h>
main()
{
 int arr1[50],arr2[50],res[150];
 int i,j,k=0,n1,n2;

 printf("Enter no of elements in array 1:");
 scanf("%d",&n1);

 printf("Enter %d elements: ",n1);
 for(i=0;i<n1;i++)
 {
  scanf("%d",&arr1[i]);
 }

 printf("\nEnter no of elements in array 2:");
 scanf("%d",&n2);

 printf("Enter %d elements: ",n2);
 for(i=0;i<n2;i++)
 {
  scanf("%d",&arr2[i]);
 }

 i=0;
 j=0;
 // Merging both array
 while(i<n1 && j<n2)
 {
  if(arr1[i] < arr2[j])
  {
   res[k] = arr1[i];
   i++;
  }
  else
  {
   res[k] = arr2[j];
   j++;
  }
  k++;
 }

 if(i >= n1)
 {

  while(j < n2)
  {
   res[k] = arr2[j];
   j++;
   k++;
  }
 }

 if(j >= n2)
 {
  while(i < n1)
  {
   res[k] = arr1[i];
   k++;
   i++;
  }
 }

 //Printing Merged Array
 printf("\nMerged array is :");
 for(i=0;i<n1+n2;i++)
 printf("%d\t",res[i]);
}

OUTPUT:

Enter no of elements in array 1: 5
Enter 5 elements: 1 3 7 12 45

Enter no of elements in array 2: 5
Enter 5 elements: 7 15 32 65 82

Merged array is :1      3       7       7       12      15      32      45      65      82

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.