11. Write a function that will merge the contents of two sorted (ascending order
ID: 3803413 • Letter: 1
Question
11. Write a function that will merge the contents of two sorted (ascending order) arrays of type double values, storing the result in an array output parameter (still in ascending order). The function should not assume that both its input parameter arrays are the same length but can assume that one array does not contain two copies of the same value. The result array should also contain no duplicate values. First array -10.5 -1.8 3.5 6.3 7.2 0 1 Second array Result array -10.5 -1.8 3.1 3.5 6.3 7.2 Hint: 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 func- tion must already be sorted.Explanation / Answer
#include <stdio.h>
void merge(int arry1[], int arry1_len, int arry2[], int arry2_len, int sorted[]);
int main()
{
int array1[] = {1,4,6,6,7};
int array2[] = {1,3,6,8,10};
int array[10];
merge(array1,5,array2,5,array);
int i=0;
for(i=0;i<10;i++){
printf("%d ",array[i]);
}
return 0;
}
void merge(int arry1[], int arry1_len, int arry2[], int arry2_len, int sorted[]) {
int i, j, k;
j = k = 0;
for (i = 0; i < arry1_len + arry2_len;) {
if (j < arry1_len && k < arry2_len) {
if (arry1[j] < arry2[k]) {
sorted[i] = arry1[j];
j++;
}
else {
sorted[i] = arry2[k];
k++;
}
i++;
}
else if (j == arry1_len) {
for (; i < arry1_len + arry2_len;) {
sorted[i] = arry2[k];
k++;
i++;
}
}
else {
for (; i < arry1_len + arry2_len;) {
sorted[i] = arry1[j];
j++;
i++;
}
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.