Suppose you have one array a[]=1,2,4,6
and a second array b[]=3,5,7
. The merged result should have all the values, i.e. c[]=1,2,3,4,5,6,7
. The merge should be done without using functions from <string.h>
.
I haven't compiled and tested the following code, but I am reasonably confident. I am assuming both input arrays are already sorted. There is more work to do to make this general purpose as opposed to a solution for this example only. No doubt the two phases I identify could be combined, but perhaps that would be harder to read and verify;
void merge_example()
{
int a[] = {1,2,4,6};
int b[] = {3,5,7};
int c[100]; // fixme - production code would need a robust way
// to ensure c[] always big enough
int nbr_a = sizeof(a)/sizeof(a[0]);
int nbr_b = sizeof(b)/sizeof(b[0]);
int i=0, j=0, k=0;
// Phase 1) 2 input arrays not exhausted
while( i<nbr_a && j<nbr_b )
{
if( a[i] <= b[j] )
c[k++] = a[i++];
else
c[k++] = b[j++];
}
// Phase 2) 1 input array not exhausted
while( i < nbr_a )
c[k++] = a[i++];
while( j < nbr_b )
c[k++] = b[j++];
}
I am learning c myself at them moment, so don't take this as the perfect solution, but maybe you can get some ideas from what I did to solve your own problem.
#include <stdio.h>
#include <stdlib.h>
int compare (const void * first, const void * second){
return *(int*)first - *(int*)second ;
}
int main(){
int a[] = {1,2,4,6};
int b[] = {3,5,7};
size_t sizeA =sizeof(a)/sizeof(a[0]);
size_t sizeB = sizeof(b)/sizeof(b[0]);
size_t sizeC = sizeA + sizeB;
/*allocate new array of sufficient size*/
int *c = malloc(sizeof(int)*sizeC);
unsigned i;
/*copy elements from a into c*/
for(i = 0; i<sizeA; ++i){
c[i] = a[i];
}
/*copy elements from b into c*/
for(i = 0; i < sizeB; ++i){
c[sizeA+i] = b[i];
}
printf("array unsorted:\n");
for(i = 0; i < sizeC; ++i){
printf("%d: %d\n", i, c[i]);
}
/*sort array from smallest to highest value*/
qsort(c, sizeC, sizeof(int), compare);
printf("array sorted:\n");
for(i = 0; i < sizeC; ++i){
printf("%d: %d\n", i, c[i]);
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With