我只是想了解递归在这个例子中是如何工作的,如果有人可以为我解决这个问题,我会很感激。我有以下算法基本上返回数组中的最大元素:
int MaximumElement(int array[], int index, int n)
{
int maxval1, maxval2;
if ( n==1 ) return array[index];
maxval1 = MaximumElement(array, index, n/2);
maxval2 = MaximumElement(array, index+(n/2), n-(n/2));
if (maxval1 > maxval2)
return maxval1;
else
return maxval2;
}
我无法理解递归调用在这里是如何工作的。第二次调用时,是否始终执行第一次递归调用?如果有人可以向我解释,我真的很感激。非常感谢!
答案 0 :(得分:2)
嵌入代码注释:
// the names index and n are misleading, it would be better if we named it:
// startIndex and rangeToCheck
int MaximumElement(int array[], int startIndex, int rangeToCheck)
{
int maxval1, maxval2;
// when the range to check is only one cell - return it as the maximum
// that's the base-case of the recursion
if ( rangeToCheck==1 ) return array[startIndex];
// "divide" by checking the range between the index and the first "half" of the range
System.out.println("index = "+startIndex+"; rangeToCheck/2 = " + rangeToCheck/2);
maxval1 = MaximumElement(array, startIndex, rangeToCheck/2);
// check the second "half" of the range
System.out.println("index = "+startIndex+"; rangeToCheck-(rangeToCheck/2 = " + (rangeToCheck-(rangeToCheck/2)));
maxval2 = MaximumElement(array, startIndex+(rangeToCheck/2), rangeToCheck-(rangeToCheck/2));
// and now "Conquer" - compare the 2 "local maximums" that we got from the last step
// and return the bigger one
if (maxval1 > maxval2)
return maxval1;
else
return maxval2;
}
使用示例:
int[] arr = {5,3,4,8,7,2};
int big = MaximumElement(arr,0,arr.length-1);
System.out.println("big = " + big);
<强>输出强>:
index = 0; rangeToCheck/2 = 2
index = 0; rangeToCheck/2 = 1
index = 0; rangeToCheck-(rangeToCheck/2 = 1
index = 0; rangeToCheck-(rangeToCheck/2 = 3
index = 2; rangeToCheck/2 = 1
index = 2; rangeToCheck-(rangeToCheck/2 = 2
index = 3; rangeToCheck/2 = 1
index = 3; rangeToCheck-(rangeToCheck/2 = 1
big = 8
答案 1 :(得分:0)
这里发生的是两个递归调用,一个接一个地进行。第一个搜索具有数组并返回最大值,第二个搜索另一半并返回最大值。然后比较两个最大值并返回更大的最大值。
答案 2 :(得分:0)
是。你猜对了是对的。在两个递归调用MaximumElement(array, index, n/2)
和MaximumElement(array, index+(n/2), n-(n/2))
中,第一次调用被重复执行,直到使用数组的单个元素进行调用。然后比较两个元素并返回最大的元素。然后继续该比较过程,直到返回最大元素。