Write a function that will merge the contents of two sorted (ascendin order) arr
ID: 3801931 • Letter: W
Question
Write a function that will merge the contents of two sorted (ascendin order) arrays of type double values, storing the result in an output array (still in ascending order). The function should not assume that both its input parameter arrays are the same length. You do not need to get the values of array elements from user, instead you may use initializer lists for the two arrays. Do NOT write any sorting function for this problem. When one of the input arrays has been exhausted, do not forget to copy the remaining data in the other array into the result array. Test your function with cases in which (1) the first array is exhausted first, (2) the second array is exhausted first, and (3) the two arrays are exhausted at the same time (i.e., they end with the same value). Remember that the arrays input to this function must already be sorted.1 Sample Output Array One: -10.50, -2.00, 0.50, 5.00, 7.00, 8.00, Array Two: -100.00, -2.00, -1.10, 1.00, 3.00, 9.00, 20.0, 34.00, Merged Array: -100.00, -10.50, -2.00, -2.00, -1.10, 0.50, 1.00, 3.00, 5.00, 7.00, 8.00, 9.00, 20.00, 34.00,Explanation / Answer
#include<stdio.h>
double * merge(double a1[], double a2[])
{
static double a3[14];
int len1 = 6;
int len2 = 8;
int i=0;
int j=0;
int k = 0;
while(i<len1&&j<len2)
{
if(a1[i]<a2[j])
{
a3[k++]=a1[i++];
}
else
{
a3[k++]=a2[j++];
}
}
while(i<len1)
{
a3[k++]=a1[i++];
}
while(j<len2)
{
a3[k++]=a2[j++];
}
return a3;
}
int main()
{
double a1[] = {-10.50,-2.00,0.50,5.00,7.00,8.00};
double a2[] = {-100.00,-2.00,-1.10,1.00,3.00,9.00,20.00,34.00};
double *a3;
a3 = merge(a1,a2);
int m;
printf("Array One : ");
for(m=0;m<6;m++)
{
printf("%lf, ",a1[m]);
}
printf(" Array Two : ");
for(m=0;m<8;m++)
{
printf("%lf, ",a2[m]);
}
printf(" Merged Array : ");
for(m=0;m<14;m++)
{
printf("%lf, ",*(a3 + m ));
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.