Search code examples
cmergesort

Mergesort implementation in C


Can someone please check my mergesort code. When I tried sorting the input values, the sorted array contained random values which weren't from input. And they were not sorted. Is the way I'm declaring array within the while loop correct?

  #include <stdio.h>
void merge (int a[], int aux[], int lo, int mid, int hi){

    for(int y=lo; y<=hi; y++){
        aux[y]=a[y];
    }
    int i=lo; 
    int j=mid+1;
    for(int k=lo;k<=mid;k++){
        if (j>hi)           a[k]=aux[i++];
        else if (i>mid)     a[k]=aux[j++];
        else if (a[j]<a[i])
        a[k]= aux[j++];
        else
        a[k]=aux[i++];
    }
return;
}


void sort (int b[],int aux[], int lo, int hi)
{ 

if(hi<=lo)
return;
int mid= lo+(hi-lo)/2;
sort(b, aux, mid+1, hi);
sort(b, aux, lo,  mid);
merge(b,aux,lo,mid,hi);
    return;
}



int main(void) {

int t,n;

long long int sum;
scanf("%d",&t);
while(t--){
    sum=0;
    scanf("%d",&n);
    int w[n];
    int m[n];
    int g[n];
    int h[n];
    for (int i=0; i<n;i++){
        scanf("%d",&m[i]);
        }


    for (int j=0; j<n;j++){
        scanf("%d",&w[j]);
}   


    sort(w,g,0,n-1);
    sort(m,h,0,n-1);

}
    return 0;
}

Solution

  • You are compareing meaningless values in the merge funtion and stop the merging in the middle of the processs.

    To correct them, in the merge function

    • Change k<=mid to k<=hi
    • Change a[j]<a[i] to aux[j]<aux[i]