Two recursive calls in a Merge Sort function confusion

前端 未结 9 1678
情书的邮戳
情书的邮戳 2021-02-19 13:37

I have been out of touch with Algorithms for a while and have start revising my concepts these days. To my surprise the last i remember of my recursions skill was that i was goo

相关标签:
9条回答
  • 2021-02-19 13:50

    The indentation in the following corresponds to the recursion:

    mergesort(0, 7)
        middle=3
        "Before the 1st Call"
        mergesort(0, 3)
            middle=1
            "Before the 1st Call"
            mergesort(0, 1)
                middle=0
                "Before the 1st Call"
                mergesort(0, 0)
                    (0 < 0) is false so return
            "After the 1st Call"
            mergesort(1, 1)
                (1 < 1) is false so return
            "After the 2nd Call"
    
            etc ...
    
    0 讨论(0)
  • 2021-02-19 13:57

    You could print out the values of high and low too. It would be much easier to follow the recursion.

    0 讨论(0)
  • 2021-02-19 14:07

    On the fourth output line, you have returned from the first call and the subsequent 2 recursive calls, so now control reaches the System.out .println ("After the 1st Call");

    So, the condition low < high is false after the second recursive call, so you just exit the function. Then, control returns to the line right after the second recursive call.

    TIP One thing I used to do when learning recursion is to keep track of stack depth (e.g. pass in a parameter for this) and then on your output you indent your output based on stack depth. This helps you visualize where you are in the recursive chain, and makes debugging easier.

    So your debugging input could look similar to the following:

    entered method, low = 0, high = 10
      entered method, low = 0, high = 5
         entered method, low = 0, high = 2
         exiting method, low = 0, high = 2
      exiting method, low = 0, high = 5
    exiting method, low = 0, high = 10
    
    0 讨论(0)
提交回复
热议问题