I can’t get his implementation of Merge Sort right. Debug it

I got it guys 🙂
While copying main array into auxiliary array in the Merge function, there was bug in the index.

int size = hi - lo + 1;
    int *aux_arr = new int[size];
    for(i = 0, j = lo;i <= size;i++){
        aux_arr[i] = first_arr[j++];
    }

Here’s the code with correction.
Also as the auxiliary array index starts from 0 to the size, I’ll have to change the index in the final merging loop

i = 0, j = mid - lo + 1;
    for(k = lo;k <= hi;k++){
        if(i > mid - lo) first_arr[k] = aux_arr[j++];
        else if(j > hi - lo) first_arr[k] = aux_arr[i++];
        else if(aux_arr[i] < aux_arr[j]) first_arr[k] = aux_arr[i++];
        else first_arr[k] = aux_arr[j++];
    }

Rest will remain same.
Thanks for commenting, it really helped. 🙂

Leave a Comment