Understanding the Recursion of mergesort

后端 未结 9 2044
感动是毒
感动是毒 2020-12-13 07:01

Most of the mergesort implementations I see are similar to this. intro to algorithms book along with online implentations I search for. My recursion chops don\'t go much fur

9条回答
  •  无人及你
    2020-12-13 07:34

    the mergesort() simply divides the array in two halves until the if condition fails that is low < high. As you are calling mergesort() twice : one with low to pivot and second with pivot+1 to high, this will divide the sub arrays even more further.

    Lets take an example :

    a[] = {9,7,2,5,6,3,4}
    pivot = 0+6/2 (which will be 3)
    => first mergesort will recurse with array {9,7,2} : Left Array
    => second will pass the array {5,6,3,4} : Right Array
    

    It will repeat until you have 1 element in each left as well as right array. In the end you'll have something similar to this :

    L : {9} {7} {2} R : {5} {6} {3} {4} (each L and R will have further sub L and R)
    => which on call to merge will become
    
    L(L{7,9} R{2}) : R(L{5,6} R{3,4})
    As you can see that each sub array are getting sorted in the merge function.
    
    => on next call to merge the next L and R sub arrays will get in order
    L{2,7,9} : R{3,4,5,6}
    
    Now both L and R sub array are sorted within
    On last call to merge they'll be merged in order
    
    Final Array would be sorted => {2,3,4,5,6,7,9}
    

    See the merging steps in answer given by @roliu

提交回复
热议问题