private void mergesort(int low, int high) { //line 1
if (low < high) { //line 2
int middle = (low + high)/2 ; //line 3
mergesort(low, middle); //line 4
mergesort(middle+1, high); //line 5
merge(low, middle, high); //line 6
}} //line 7
我理解当 if 语句为 false 时退出方法/函数的事实。例如,如果我在 main 方法中调用 mergesort(0, 5)
,第一个 mergesort(low, middle)
将运行 3 次并终止,然后程序将继续到第 7 行。
令我感到困惑的是,为什么当程序返回到第 5 行的 mergesort(middle+1, high);
时,high
突然从 0 变为 1。
这是另一个类似但更简单的程序示例
public static void recursionExample(int i){ //line 1
if(i < 3){ //line 2
recursionExample(i+1); //line 3
recursionExample(i-1); //line 4
} //line 5
} //line 6
这次如果我调用 recursionExample(0)
第 3 行的 recursion(i+1);
将运行 3 次,直到 if 语句为假,然后它会去到第 6 行,然后程序将转到第 4 行 recursion(i-1);
然而,当它从第6 到第 4 行。这是我觉得最令人困惑的地方。为什么调用第二个递归方法时i变成了2。
最佳答案
关于你的第二个片段:
public static void recursionExample(int i){
if(i < 3){
recursionExample(i+1); // this is called for the last time when i==2, i.e. the
// last call is recursionExample(3). When that call
// returns, i is still equal 2, since calling
// recursionExample(i+1) doesn't change the value of the
// local variable i of the current method call
recursionExample(i-1); // Therefore when this line is first called, i is equal 2
}
}
关于java - 合并排序中的递归 : two recursive calls,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34481281/