我正在寻找一种递归方法来查找数组中的最大值(我已经知道迭代的一个) 对于基本情况,我想出了:
if(t.length == 1)
return t[0];
但我不知道递归调用步骤 如果有人能帮助我,我会很高兴
答案 0 :(得分: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);
}
}
答案 1 :(得分: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));
}
}