简体   繁体   English

递归函数以查找数组中的最大值

[英]Recursive function to find largest in Array

I have this so far, I just need it to start at any index value given by a parameter, how would I add this. 到目前为止,我已经有了它,我只需要它从参数给定的任何索引值开始,我将如何添加它。

    public static int maxElement(int[] a, int i){
    if (i > 0) {
        return Math.max(a[i], maxElement(a, i-1));
    } 

   else {
        return a[0];
    }
}

(not including code, as it is really trivial) (不包括代码,因为它确实是微不足道的)

if you need to search for max element from index i to the end of array 如果您需要搜索从索引i到数组末尾的max元素

1) use i as start index as @pbabcdefp instructed 1)按照@pbabcdefp的指示使用i作为起始索引

2) in recursion check use array length, not zero 2)在递归检查中使用数组长度,不为零

3) increment i in the recursion call 3)在递归调用中增加i

4) fall back to i -th element when reached end of array 4)到达数组末尾时退回到第i -th个元素

that's it 而已

public static int maxIndex(int i, int[] a){
   if(i == a.length - 1) return a.length - 1;
   int j = maxIndex(i+1, a);
   if(a[i] > a[j])
     return i;
   return j;
}

Use it by: 使用方式:

System.out.println(a[maxIndex(0, a)]);
public static int maxElement(int[] a, int i) {
  if (i < a.length - 1) {
    return Math.max(a[i], maxElement(a, i+1));
  } else {
    return a[a.length - 1];
  }
}

Go forward, adjust boundaries and you're done. 前进,调整边界,您就完成了。

public static int maxElement(int[] array, int index){
    //check all elements from index
    if (index >= 0 && index < array.length - 1) {
        return Math.max(array[index], maxElement(array, index+1));
    }
    // return last element
    return array[array.length -1];
}

maxElement method: maxElement方法:

public static int maxElement(int[] a, int i) throws IndexOutOfLenght{

    if (i > a.length-1 || i < 0)
        throw new IndexOutOfLenght();
    else{
        if (i == a.length-1)
            return a[i];
        else            
            return Math.max(a[i], maxElement(a, i+1));
    }
}

Main: 主要:

public static void main(String[] args) throws IndexOutOfLenght {
    int[] array = {1,2,3,4,5,6};
    System.out.println(maxElement(array,1));
}

Exception class: 异常类:

public class IndexOutOfLenght extends Exception {
     IndexOutOfLenght() {
        super("IndexOutOfLenght ");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM