找到一个数组的最大元素递归

编程入门 行业动态 更新时间:2024-10-11 17:29:38
本文介绍了找到一个数组的最大元素递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

考虑这个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.

更多推荐

找到一个数组的最大元素递归

本文发布于:2023-11-29 10:16:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646112.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   数组   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!