我正在尋找一個遞歸方法來找到數組中的最大值(我知道已經是迭代的) 對於基本情況,我提出了這個想法即:使用遞歸在數組中尋找最大值java
if(t.length == 1)
return t[0];
,但我不知道遞歸調用一步 我會很高興,如果有人可以幫助我
我正在尋找一個遞歸方法來找到數組中的最大值(我知道已經是迭代的) 對於基本情況,我提出了這個想法即:使用遞歸在數組中尋找最大值java
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);
}
}
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));
}
}
HTTP://www.danzig。我們/ JAVA_CLASS/R ecursion.html –
@HussainAkhtarWahid就是我在我的問題中寫的那個:p –
在這種情況下,您實現遞歸有點遠。 (或找到最大的價值) –