Search code examples
javarecursiondivide-and-conquer

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

}

Solution

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