我一直在尝试学习分而治之的算法,并想出了我认为使用java会奏效的方法。该算法应该采用一个大小为n的数组,该数组的基数为2。它应该将数组划分为基数为4的大小写,然后将索引的大小写相加。然后,它将所有这些加在一起,得出整个数组的和。以下是我迄今为止在java中所做的工作和我的错误。我至少走上了分而治之算法的正确轨道吗?
引发异常:
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)
这是代码:
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));
}
}