Divide and conquer Algorithm

I am learning divide and conquer algorithms in school and I am having some trouble figuring it out. I am required to find the sum of an array but divide and conquering an array to base case 4 then finding the sum of those 4 numbers. I think I have the basic idea of divide and conquer, but I cannot get my code below to work.

I keep getting this error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8

at getSum.sumArray(getSum.java:17)

at getSum.sumArray(getSum.java:21)

at getSum.main(getSum.java:7)

Code :

public class getSum {
static int sum = 0;
public static void main(String[] args) {
int[] numbers = {2,2,2,2,2,2,2,2};
int amount = 0;
amount = sumArray(0,numbers.length,numbers);
System.out.print(amount);
}
public static int sumArray(int first, int last, int[] A){
int index = last - first;
if(index == 1){
return sum;
}else if(index <= 4 && index > 1){
for(int i = first; first < last; i++){
sum += A[i];
}
return sum;
}
return (sumArray(first, last / 2, A) + sumArray(last / 2, A.length, A));
}
}

Re: Divide and conquer Algorithm

Quote:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8

at getSum.sumArray(getSum.java:17)

The code at line 17 uses an index that is past the end of the array.

Remember that array indexes range from 0 to the array length-1

If you can't see how the variable's value gets its value, add some println calls to print out the values of the variables so you can see what the computer see.