Write a program to merge two sorted array & no element is repeated during merging.

 Code:-

#include<stdio.h>
int main()
{
int a[50],b[50],i,j,k,n1,n2,c[100];
printf(“Enter the lenght of both arrayn”);
scanf(“%d%d”,&n1,&n2);
printf(“Enter first sorted arrayn”);
for(i=0;i<n1;i++)
scanf(“%d”,&a[i]);
printf(“Enter second sorted arrayn”);
for(i=0;i<n2;i++)
scanf(“%d”,&b[i]);
// logic for merging the arrays
i=j=k=0;
while(i<n1 && j<n2)
{
if(a[i]>b[j])
{
c[k]=b[j];
j++;
}
else
{
if(a[i]==b[j])
{
c[k]=b[j];
j++;
i++;
}
else
{
c[k]=a[i];
i++;
}
}
k++;
}
// copying remaing element of the first array
// (if remaing)
while(i<n1)
{
c[k]=a[i];
k++;
i++;
}
// copying remaing element of the second array
while(j<n2)
{
c[k]=b[j];
j++;
k++;
}
printf(“The merge array is: “);
for(i=0;i<k;i++)
printf(“%d “,c[i]);
return 0;
}

Output:-

Enter the lenght of both array
5 5
Enter first sorted array
1 12 23 45 56
Enter second sorted array
2 3 4 12 23
The merge array is: 1 2 3 4 12 23 45 56



Leave a Reply

Your email address will not be published.