My Merge Sort program is not working as it should

Solution 1:

The problem is with k:

As you use k as index in temp, you should not let k start at l, but at 0. Your code will access memory outside of the range of temp, and that gives undefined results or a segmentation fault. For the same reasons, in the final loop, where you copy from temp, you cannot use the same index value for temp and for x. You'll want to copy temp[0] to x[l], temp[1] to x[l+1], ...etc.

So change:

k = l;

to:

k = 0;

And change:

for (i = l; i < k; i++)
   x[i] = temp[i];

to:

for (i = 0; i < k; i++)
   x[l + i] = temp[i];