使用递归java查找数组中的最大值
我正在寻找一种递归方法来查找数组中的最大值(我已经知道迭代方法) 对于基本情况,我提出了以下想法:使用递归java查找数组中的最大值,java,recursion,max,Java,Recursion,Max,我正在寻找一种递归方法来查找数组中的最大值(我已经知道迭代方法) 对于基本情况,我提出了以下想法: if(t.length == 1) return t[0]; 但我不知道递归调用步骤 如果有人能帮助我,我将非常高兴 int largest(int[] a, int start, int largest) { if (start == a.length) return largest; else { int l = (a[start] &g
if(t.length == 1)
return t[0];
但我不知道递归调用步骤
如果有人能帮助我,我将非常高兴
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);
}
}
导入java.util.array
公共类RecMax{
公共静态void main(字符串[]args){
int值[]={1,2,3,4,5,10,8,9,7,3,2,8};
int maxvalue=max(Integer.MIN_值,值);
系统输出打印项次(最大值);
}
公共静态int max(int cur,int[]值){
//只是为了澄清
int len=value.length;
//停止条件
//如果已检查所有数组,则cur包含最大值
如果(len==0){
返回电流;
}
//如果数组的最后一个元素大于当前元素,则为
//新的临时最大值,否则当前最大值就是已找到的最大值
int tmpMax=值[len-1]>cur?值[len-1]:cur;
//递归
//检查阵列的其余部分(len-1)
//复制数组是一种浪费,但我很清楚递归的含义
返回最大值(tmpMax,Arrays.copyOfRange(值0,len-1));
}
}
@HussainAkhtarWahid正是我在问题中写的一个:如果是这样的话,你离实现递归有点远。(或者找到最大值)@navidkoochoolo你应该在问这个问题之前付出一些努力,谷歌:给你,如果我们在方法中传递最大值,使用它的意义是什么:)在连续的方法调用堆栈中获得最大值。我不认为像那样粘贴代码是一个很好的答案。你不应该试着描述一下代码的功能和调用方式吗?他应该使用什么作为
开始
和最大
参数的开始值。另外,使用尾部递归也很好,但对于初学者来说,非尾部递归方法有时更容易解释和理解。JVM还不支持尾部调用优化,我想他们是在展示收集“状态”和成就的代码。而不是显示方向或提示
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));
}
}