找到一个数组的最大元素递归 [英] Finding the maximum element of an array recursively
问题描述
考虑这个code,它计算一个数组的最大元素。
Consider this code, which computes the maximum element of an array.
#include <stdio.h>
int maximum(int ar[], int n)
{
if (n == 1) {
return ar[0];
} else {
int max = maximum(ar, n-1);
printf("Largest element : %d\n", max);
return 5; // return ar[n-1] > max ? ar[n-1] : max;
}
}
int main()
{
int array[5] = {5, 23, 28, 7, 1};
printf("Maximum element of the array is: %d", maximum(array, 5));
return 0;
}
为什么叫else块四次?
Why is the else block called four times?
推荐答案
函数是递归的,所以它会被多次调用。
The function is recursive, thus it will be called multiple times.
当你第一次启动,N = 5。这将需要else块(n是不是1)。
然后,您有n-1再次调用最大值(N = 4)。同样,其他块服用。
When you first start, n=5. It will take the else block (n is not 1). Then, you call maximum again with n-1 (n=4). Again, the else block is taken.
总而言之,函数被调用4次n达到1日前,于是它采取if块并返回AR [0]
All told, the function is called 4 times before n reaches 1, whereupon it takes the if block and returns ar[0].
正如其他人提及的,作为写入的功能将不会返回列表的最大值。奇怪的是,它似乎总是返回5除非列出数组大小为1,在这种情况下,它返回该元素的值。
As others have mentioned, the function as written will not return the maximum value of the list. Curiously, it seems to always return 5 unless the list array size is 1, in which case it returns the value of that element.
相反,递归方法将通常涉及分割成两半,每次列表中,然后返回每一对的最大当列表终于分成元素对。
Instead, a recursive approach would typically involve splitting the list in half each time, then returning the max of each pair when the list finally broken into pairs of elements.
这篇关于找到一个数组的最大元素递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!