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
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 ...
You could print out the values of high
and low
too. It would be much easier to follow the recursion.
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