简体   繁体   中英

Merge sort Recursion Error

   Mergesort(a,p,r){
     if(p<r){
       int q=[p+r]/2;
       Mergesort(a,p,q);
       Mergesort(a,q+1,r);
       Merge(a,p,q,r);

It's from the book Introduction to ALgorithms:Cormen in this i can't understand the recursive call of the merge sort algorithm

                   2 4 1 6 8 5 3 7 
               2 4 1 6         
              2 4 
             2

in the first recursive call i got upto three then where does the control goes from here im struck at 2 will it call the next function mergesort(a,q+1,r) and merge(a,p,q,r) ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM