So I have two arrays consisting of double numbers, they are sorted.
I would like to most efficiently combine these into one array and have this one array also sorted.
My first thought was that maybe you could simply join them together then use qsort on it, but this wouldn't be that efficient. So maybe instead using merge sort? However, I am kind of lost on how to implement merge sort in C, any ideas?
I am using the code from one of the answers to try merge sorting. I have not made it into its own method just yet, will do that after I have gotten it to work.
double partitions[][5] = {{45.0, 5.0, 88.4, 0.4, 44.0}, {1000.0, 2.0, 3.4, 7.0, 50.0}};
double* res;
int n1 = sizeof(partitions[0])/sizeof(partitions[0][0]);
int n2 = sizeof(partitions[1])/sizeof(partitions[1][0]);
int n3 = n1 + n2;
res = malloc(n3 * sizeof(double));
// Merging starts
int i = 0;
int j = 0;
int k = 0;
while (i < n1 && j < n2) {
if (partitions[0][i] - partitions[1][j] < 0.000001) {
res[k] = partitions[0][i];
i++;
k++;
}
else {
res[k] = partitions[1][j];
k++;
j++;
}
}
/* Some elements in array 'arr1' are still remaining
where as the array 'arr2' is exhausted */
while (i < n1) {
res[k] = partitions[0][i];
i++;
k++;
}
/* Some elements in array 'arr2' are still remaining
where as the array 'arr1' is exhausted */
while (j < n2) {
res[k] = partitions[1][j];
k++;
j++;
}
int m;
for (m = 0; m < n3; m++)
printf("%f \n", res[m]);