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 に答える