Understanding the Recursion of mergesort

后端 未结 9 2054
感动是毒
感动是毒 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:37

    When you call the recursive method it does not execute the real function at the same time it's stack into stack memory. And when condition not satisfied then it's going to next line.

    Consider that this is your array:

    int a[] = {10,12,9,13,8,7,11,5};
    

    So your method merge sort will work like below:

    mergeSort(arr a, arr empty, 0 , 7);
    mergeSort(arr a, arr empty, 0, 3);
    mergeSort(arr a, arr empty,2,3);
    mergeSort(arr a, arr empty, 0, 1);
    
    after this `(low + high) / 2 == 0` so it will come out of first calling and going to next:
    
        mergeSort(arr a, arr empty, 0+1,1);
    
    for this also `(low + high) / 2 == 0` so it will come out of 2nd calling also and call:
    
        merger(arr a, arr empty,0,0,1);
        merger(arr a, arr empty,0,3,1);
        .
        .
        So on
    

    So all sorting values store in empty arr. It might help to understand the how recursive function works

提交回复
热议问题