简体   繁体   中英

Finding the max number with Divide and Conquer in Java

I'm trying to find the maximum number in an array using Divide and Conquer Method(recursion). But when I compile this code, I'm getting ArrayIndexOutOfBounds exception.

I'm not sure where I'm going wrong. Here is my code snippet:

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

}

I don't think this is the best use of recursion. However, this would be easier to follow I think. Hope it helps, cheers!

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

The problem is in your last line:

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

This will use the results of your findMax() methods as arguments for another findMax() call, which means they will be used as indexes to the array. That will give you a wrong result or cause an ArrayIndexOutOfBoundsException .

What you want to do is return the maximum of the two findMax() calls:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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