2013-06-12 73 views
0

我正在寻找一个递归方法来找到数组中的最大值(我知道已经是迭代的) 对于基本情况,我提出了这个想法即:使用递归在数组中寻找最大值java

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

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

+0

HTTP://www.danzig。我们/ JAVA_CLASS/R ecursion.html –

+0

@HussainAkhtarWahid就是我在我的问题中写的那个:p –

+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); 
    } 
} 
+0

如果我们通过最大的方法,使用它的意义是什么:) –

+0

要弄清楚连续方法调用堆栈中最大的值。 – NINCOMPOOP

+0

唉唉⋯⋯⋯⋯ –

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)); } }