Given two sorted arrays, merge them into single array such that the elements are not repeated.
For Example:
Input:
Array1: 2 4 5 6 7 9 10 13
Array2: 2 3 4 5 6 7 8 9 11 15
Output: 2 3 4 5 6 7 8 9 10 11 13 15
Implementation:
For Example:
Input:
Array1: 2 4 5 6 7 9 10 13
Array2: 2 3 4 5 6 7 8 9 11 15
Output: 2 3 4 5 6 7 8 9 10 11 13 15
Implementation:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *s,*v,*c;
int n,x;
int l,r,t;
int i;
/* Get the size of the first sorted array */
scanf("%d",&n);
/* allocate memory for the first array */
s=(int*)malloc(sizeof(int)*n);
/* Get the size of the second sorted array */
scanf("%d",&x);
/* allocate memory for the second array */
v=(int*)malloc(sizeof(int)*x);
/* Get the values of the first sorted array */
for(i=0;i<n;i++)
scanf("%d",(s+i));
/* Get the values of the second sorted array */
for(i=0;i<x;i++)
scanf("%d",(v+i));
/* Allocate memory for the resultant array */
c=(int*)malloc(sizeof(int)*(n+x));
/* Initialize counter variables for array1, array2, result array */
l=0;
r=0;
t=0;
/* Until we reach the end of any one of the array */
while(l<n && r<x)
{
/* Check if the value of the both arrays are equal
If yes, copy value from any one of the array */
if(*(s+l)==*(v+r))
{
c[t++]=*(s+l);
/* Increment both of the array pointers */
l++;
r++;
}
/* If the value of array1 is less than the value of array2
copy the value of array1 & move the pointer of array 1*/
else if(*(s+l)<*(v+r))
{
c[t++]=*(s+l);
l++;
}
/* Else copy the value of array2 & move the pointer of array2*/
else
{
c[t++]=*(v+r);
r++;
}
}
/* We reached the end of array 1*/
if(l==n)
{
/* But yet we did't reached the end of array 2 */
while(r<x)
{
/* Copy all the remaining elements of array 2 to result array */
c[t++]=*(v+r);
r++;
}
}
else
{
while(l<n)
{
/* Else, copy all the remaining elements of array 1 to result array */
c[t++]=*(s+l);
l++;
}
}
/* Print the result array */
for(i=0;i<t;i++)
printf("%d ",*(c+i));
return 0;
}
Input:
8
10
2 4 5 6 7 9 10 13
2 3 4 5 6 7 8 9 11 15
Output:
2 3 4 5 6 7 8 9 10 11 13 15