On-site merging is possible, but it gets more complicated and doesn't give a big gain in performance. Below is a sample code here . from is your leftPos , to is your rightPos , pivot is your (rightPos-leftPos)/2 , and lengths are the lengths of each half.
void merge(int from, int pivot, int to, int len1, int len2) { if (len1 == 0 || len2==0) return; if (len1+len2 == 2) { if (compare(pivot, from) < 0) exchange(pivot, from); return; } int first_cut, second_cut; int len11, len22; if (len1 > len2) { len11=len1/2; first_cut = from + len11; second_cut = lower(pivot, to, first_cut); len22 = second_cut - pivot; } else { len22 = len2/2; second_cut = pivot + len22; first_cut = upper(from, pivot, second_cut); len11=first_cut - from; } rotate(first_cut, pivot, second_cut); int new_mid=first_cut+len22; merge(from, first_cut, new_mid, len11, len22); merge(new_mid, second_cut, to, len1 - len11, len2 - len22); }
source share