Suppose your array is a = { 2, 4, 6, 1, 8, 5, 3, 7 }
. I swapped two elements of the array proposed by you. Now, what follows is exactly what your program does, call after call.
At the first call p=0, q=7
: your while array is the input.
At the second call p=0, q=3
, at the third p=0, q=1
.
At the fourth call p=0, q=0
: the input is the subarray { 2 }
. This array has just one element, thus is sorted: the line if(p<r)
makes sure the fourth call ends here and control returns to the third call.
The third call has the input { 2, 4 }
. We have just ended the line Mergesort(a,p,q);
, thus we know the first half of the input is sorted. The fifth call (line Mergesort(a,q+1,r);
) will now sort the second half.
At the fifth call p=1, q=1
. The input is once again an array of length 1, thus sorted by default. Control returns to the third call.
The third call is now evaluating the line Merge(a,p,q,r);
. The first half is sorted, the second half is sorted: Merge(a,p,q,r);
takes those two halves and shifts the element making sure the whole subarray from index p
to index r
is sorted. The third call ends.
The second call had { 2, 4, 6, 1 }
has input. The first half is sorted, now remains the second half: after that call the input become { 2, 4, 1, 6 }
. After Merge
is called the input become { 1, 2, 4, 6 }
and the second call ends, returning control to the first call.
The first call now needs to sort the second half of its input, that incidentally is the whole array. That is done as before.