0

So, I have been trying to understand how to do recursive merge sort using a wrapper function. But using the Wrapper function and W( see code), how do I write the merge function to actually combine the arrays to get the solution?

//Recursive mergesort in C
#include<stdio.h>
#include<stdlib.h>
void Srec(int *A, int n, int* W);
void Msort(int *A, int n);

void merge(){

//How to write this?

}

void Srec(int *A, int n, int* W){    //Function to recursively sort the arrays
    if(n<=1){
        return;
    }
    Srec(A,n/2,W); //First half
    Srec((A+(n/2)),(n-(n/2)),W); // second half
    merge(W,n,A);   // Here is where I called merge...
}

void Msort(int *A, int n){     // Wrapper function
    int* W = (int*) calloc(20,sizeof(int));    // Creates dyn. array with size 20
    Srec(A,n,W);
    free(W);
}

int main(int argc, char const *argv[])
{
    int* A = (int*) calloc(20,sizeof(int));
    int B[] = {1,3,2,4,7,6,5,0,9,10};
    A = B;
    int n = 10;
    Msort(A,n);
    return 0;
}
  • Three unrelated things: First of all `A = B` doesn't do what you probably think it does (it does not copy the array); Secondly you're calling `free(W)` more than should be done; And thirdly in C you [shouldn't really cast the result of `malloc` or `calloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Some programmer dude Feb 03 '21 at 18:14
  • @Someprogrammerdude actually it does! When I added a for loop inside the Srec function to print the array A, it printed out elements of array B for me. – technextgen Feb 03 '21 at 18:16
  • The purpose of the wrapper function is to create the scratch array `W`. Your merge funtion is like a normal merge function, only that istead of local arrays you use the array `W`. And please, don't make a guess for the size of `W` when you have exact data. You allocate space for 20 ints, but you need space for `n` ints. – M Oehm Feb 03 '21 at 18:19
  • "... to print the array A, it printed out elements of array B" – yes, because after the assignment `A` is a pointer to the first element of `B` and the previously allocated space for 20 ints is lost. The assignment `A = B` does not copy the elements, it makes A an alias for B. – M Oehm Feb 03 '21 at 18:23
  • Actually, `A = B` makes `A` ***point to*** the first element of `B`. It's equal to `A = &B[0]`. The original value of `A` is lost. What you're doing is similar to `int A = 10; int B = 20; A = B;` and then wonder why `A` isn't equal to `10` anymore. – Some programmer dude Feb 03 '21 at 18:23
  • @Someprogrammerdude Then what is the best way to allocate static values to a malloc array? – technextgen Feb 03 '21 at 19:37
  • Do you really need the memory you allocate? Why not sort `B` directly? But if you need to keep it without modificationd then [copy its contents](https://en.cppreference.com/w/c/string/byte/memcpy). – Some programmer dude Feb 03 '21 at 22:19

0 Answers0