0

我正在寻找一种递归方法来找到基本情况的数组中的最大值(我已经知道迭代的),我想出了这样的想法:

if(t.length == 1)
   return t[0];

但我不知道递归调用步骤,如果有人可以帮助我,我会很高兴

4

2 回答 2

1
int largest(int[] a, int start, int largest) {
    if (start == a.length)
        return largest;
    else {
        int l = (a[start] > largest ? a[start] : largest);
        return largest(a, start + 1, l);
    }
}
于 2013-06-12T09:26:26.920 回答
0


import java.util.Arrays;

public class RecMax { public static void main(String[] args) {

int values[] = {1,2,3,4,5,10,8,9,7,3,2,8}; int maxvalue = max(Integer.MIN_VALUE, values); System.out.println(maxvalue); } public static int max(int cur, int[] values) { //just for clarity int len = values.length; //stop condition //if all the array has been examined than cur contains the max if (len == 0) { return cur; } //if the last element of the array is greater than the current then this is //the new temporary max, else the current max is the one already found int tmpMax = values[len - 1] > cur ? values[len - 1] : cur; //recursion //examine the remaining part of the array (len -1) //copying the array is a waste but it looks clear to me what a recursion means return max(tmpMax, Arrays.copyOfRange(values, 0, len - 1)); } }
于 2013-06-12T09:49:29.053 回答