Hi, the exercise is this:
I got two sorted arrays (of any length) and I got to merge them into a new array (of correct length, and still sorted), recursively.
I solved the problem like this:
Code:
#include <stdio.h>
#include <stdlib.h>
void merge(int *v1, int *v2, int l1, int l2, int *v3);
int *newArray(int n);
int main (void) {
int *v1, *v2, *v3;
int i, l1, l2, l3;
v1 = v2 = v3 = NULL;
printf("Enter the numbers in increasing order.\n\n");
printf("First's array length: ");
do{
scanf("%d", &l1);
}while(l1 <= 0);
v1 = newArray(l1);
printf("\nSecond's array length: ");
do{
scanf("%d", &l2);
}while(l2 <= 0);
v2 = newArray(l2);
l3 = l1 + l2;
v3 = malloc(l3 * sizeof(int));
if(!v3)
return -1;
merge(v1, v2, l1, l2, v3);
printf("\nResult:\n");
for(i=0; i<l3; ++i)
printf("%d ", v3[i]);
return 0;
}
void merge(int *v1, int *v2, int l1, int l2, int *v3){
if(l1 && l2){ // verifying if both vectors got elements
if(*v1 <= *v2){
*v3 = *v1;
merge(++v1, v2, --l1, l2, ++v3);
}
else{
*v3 = *v2;
merge(v1, ++v2, l1, --l2, ++v3); // notare ++v2 e --l2 e ++v3
}
}
else if(l1){ // verifying if only v1 got elements
*v3 = *v1;
merge(++v1, v2, --l1, l2, ++v3);
}
else if(l2){ // verifying if only v2 got elements
*v3 = *v2;
merge(v1, ++v2, l1, --l2, ++v3);
}
}
int *newArray(int n){
int *v = NULL;
int i;
v = malloc(n * sizeof(int));
if(!v)
return NULL;
for(i=0; i<n; ++i){
printf("[%d]: ", i);
scanf("%d", &v[i]);
}
return v;
}
My solution seems to work well. I only got a doubt about how I solved it, it is: is there a way to make it in the form "v3 = merge(parameters);" ?
I would like to know if I can do it with returns... it would be a non-void function.
Thanks