Random values when using merge in merge sort C++ Random values when using merge in merge sort C++ arrays arrays

Random values when using merge in merge sort C++


The problem is that you are computing the number of entries in temp incorrectly: your code thinks it is right_high + 1, but the correct formula is right_high - left_low + 1.

For example, when a call gives you indexes 10, 15, 16, 26, your code tries to merge 27 values, while it should be merging only 17 (i.e. indexes 10 through 26, inclusive).

This makes no difference when left_low is zero, so your test case runs fine. But as soon as left_low becomes nonzero, e.g. when the right half of the array is being sorted, your code "overshoots" both arrays, placing garbage values into tmp and writing over values in the array a as well.

Also the assignments in the last for loop need to be at offset left_low as well:

for(int i = 0; i < temp_i; ++i)    a[i+left_low] = temp[i];