Given two sorted arrays, of equal size, merge them into one single array
Implemenation:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a,*b,n,i,*temp,l=0,r=0;
/* get the number of elements */
scanf("%d",&n);
/* size allocation for the arrays */
a=(int*)malloc(sizeof(int)*n);
b=(int*)malloc(sizeof(int)*n);
temp=(int*)malloc(sizeof(int)*2*n);
/* get the array a */
for(i=0;i<n;i++)
scanf("%d",(a+i));
/* get the array b */
for(i=0;i<n;i++)
scanf("%d",(b+i));
i=0;
/* while any one of the arrays becomes empty, copy the least element in to temp array */
while(l<n && r<n)
{
if(*(a+l)<*(b+r))
{
*(temp+i)=*(a+l);
i++;
l++;
}
else
{
*(temp+i)=*(b+r);
i++;
r++;
}
}
/* If still array b is not empty, copy the elements to the array temp */
if(l==n)
{
while(r<n)
{
*(temp+i)=*(b+r);
i++;
r++;
}
}
/* If still array a is not empty, copy all the elements of the array a to temp array */
else
{
while(l<n)
{
*(temp+i)=*(a+l);
i++;
l++;
}
}
/* Print the resultant array */
for(i=0;i<2*n;i++)
printf("%d ",*(temp+i));
return 0;
}