Few things here...
the format of your input paramtersparameters is inconvenient. You should probably just replace the
beginandendparameters with a singlesize. The method can then be called as:mergesort2(list, middle, tmplist); mergesort2(list + middle, end - middle, tmplist);this also fixes a lot of
+1offsets you have where theendindex is not convenient. It will also remove a lot of math where you are doingend-begin+1or equivalent.consider changing your mid-point calculation to be:
int midddlemiddle = begin + (end - begin) / 2;This avoids a bug when
beginandendare large values, and the sum of them overflows theint.Actually, if it were me, I would be using the size method above, and I would declare
middleto be 1 different than you:int midddlemiddle = (size + 1) / 2;this makes the second 'half' the 'smaller' half, and it removes all the '+1' offsets you have to apply later in the code (it also changes some other range checks/limits), but, overall it will simplify the code.
Small nit-pick - I dislike magic numbers, especially 'vagrant'
+ 1values... consider this line here:for (int first=begin, second=middle+1, tmp=0; tmp<end-begin+1; tmp++) {This
+1could be avoided with (if you have a good size, and middle):for (int first=begin, second=middle, tmp=0; tmp<size; tmp++) {performance/correctness: declare
beginandendto be constants in the method signature.performance/correctness: inside your loop you have two conditions:
if (first > middle) { .... } else if (second > end) { .... }inside each of those blocks you should
break;so that you do not need to repeatedly copy the memory which does not need merging.