#include<stdio.h>
int main()
{
int a[20],b[20],c[40],i,j,k,n1,n2;
clrscr();
printf("Merging 2 sorted arrays...\n\n");
//array 1 input
printf("Enter how many elements in array1: ");
scanf("%d",&n1);
for(i=0;i<n1;i++)
{
printf("Enter element %d: ",i+1);
scanf("%d",&a[i]);
}
//array 2 input
printf("Enter how many elements in array2: ");
scanf("%d",&n2);
for(i=0;i<n2;i++)
{
printf("Enter element %d: ",i+1);
scanf("%d",&b[i]);
}
//merging
for(i=0,j=0,k=0;i<n1&&j<n2;k++)
{
if(a[i]<b[j])
{
c[k]=a[i];
i++;
}
else if(a[i]==b[j])
{
c[k]==a[j];
j++;
}
else
{
c[k]=b[j];
j++;
}
}
//remaining elements of array 1
while(i<n1)
{
c[k]=a[i];
i++;
k++;
}
//remaining elements of array 2
while(j<n2)
{
c[k]=b[j];
j++;
k++;
}
//output
printf("\n\nArray after merging elements of both arrays are..\n");
for(i=0;i<(n1+n2);i++)
printf("%d\t",c[i]);
return 0;
}
int main()
{
int a[20],b[20],c[40],i,j,k,n1,n2;
clrscr();
printf("Merging 2 sorted arrays...\n\n");
//array 1 input
printf("Enter how many elements in array1: ");
scanf("%d",&n1);
for(i=0;i<n1;i++)
{
printf("Enter element %d: ",i+1);
scanf("%d",&a[i]);
}
//array 2 input
printf("Enter how many elements in array2: ");
scanf("%d",&n2);
for(i=0;i<n2;i++)
{
printf("Enter element %d: ",i+1);
scanf("%d",&b[i]);
}
//merging
for(i=0,j=0,k=0;i<n1&&j<n2;k++)
{
if(a[i]<b[j])
{
c[k]=a[i];
i++;
}
else if(a[i]==b[j])
{
c[k]==a[j];
j++;
}
else
{
c[k]=b[j];
j++;
}
}
//remaining elements of array 1
while(i<n1)
{
c[k]=a[i];
i++;
k++;
}
//remaining elements of array 2
while(j<n2)
{
c[k]=b[j];
j++;
k++;
}
//output
printf("\n\nArray after merging elements of both arrays are..\n");
for(i=0;i<(n1+n2);i++)
printf("%d\t",c[i]);
return 0;
}
1 comment:
if(a[i]==b[j])
{
c[k]=a[i];
i++;
j++;
}
Post a Comment