I have been trying to learn divide and conquer algorithms and I have come up with what I thought would work using java. The algorithm is supposed to take an array of size n that is a base 2. It should divide the array to a base case of 4 then add those for indexes together. Then it will add all those together to find the sum of the entire array. Here is what I have done so far in java and my error. Am I at least on the right track for the divide and conquer algorithms?
Exception raised:
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)
Here is the 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));
}
}
You need to change:
to:
You keep comparing
firstandlast, when you increment onlyiAnd as @Some1.Kill.The.DJ pointed out,
sumshould be part of methodsumArray