繁体   English   中英

用Java中的分而治之查找最大数

[英]Finding the max number with Divide and Conquer in Java

我正在尝试使用分而治之方法(递归)在数组中找到最大数量。 但是当我编译这段代码时,我得到了ArrayIndexOutOfBounds异常。

我不确定我要去哪里。 这是我的代码段:

public class ... {
  int[] A = {2,4,5,1,6,7,9,3};
  int max;

  public void solution() {
    max = findMax(0, A.length-1);
    //print max
  }

  private int findMax(int a, int b){    
    if(b-a == 1){
        return A[a]>A[b] ? A[a] : A[b];
    }
    else if(a==b){
        return A[a];
    }

    return findMax(findMax(a, (a+b)/2), findMax((a+b)/2 +1, b));
  }

}

我认为这不是递归的最佳使用。 但是,我认为这会更容易理解。 希望能有所帮助,加油!

public static int maxI(int[] x, i index){
  if (index > 0) 
  {
    return Math.max(x[i], maxI(x, i-1))
  } 
  else 
  {
    return x[0];
  }
}

问题出在最后一行:

return findMax(findMax(a, (a+b)/2), findMax((a+b)/2 +1, b));

这会将findMax()方法的结果用作另一个findMax()调用的参数,这意味着它们将用作数组的索引。 那会给你一个错误的结果,或者导致ArrayIndexOutOfBoundsException

您想要做的是返回两个findMax()调用中的最大值:

return Math.max(findMax(a, (a+b)/2), findMax((a+b)/2 + 1, b));

暂无
暂无

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

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