Hey everyone, well I'm like 5/6s complete with my assignment (out of 6 methods, I've completed 5), all on recursion. I'm having a little trouble with this last one though, I have to recursively add the left side of an array, then add the middle element, then add the right side, "divide and conquer" basically.
This is what I have so far (sorry if its a little messy,the copy/paste kind of messed it up):
Its throwing an array out of bounds error, I'm assuming because its trying to do a[5] (I'm using a 5 element array, so the highest is a[4]).
Thanks!
This is what I have so far (sorry if its a little messy,the copy/paste kind of messed it up):
Code:
public static int sum(int a[], int lf, int rt) {
int sum = 0;
int left = 0;
int right = 0;
if(a.length == 0) {
sum = 0;
} else if(lf > rt) {
//
} else {
if(lf < rt) {
System.out.println("lf " + lf + " right " + rt);
int mid = (lf + rt) / 2;
System.out.println(mid);
left = left + a[sum(a, lf, mid-1)];
right = right + a[sum(a, mid+1, rt)];
sum = left + mid + right;
}
}
return sum;
}
Its throwing an array out of bounds error, I'm assuming because its trying to do a[5] (I'm using a 5 element array, so the highest is a[4]).
Thanks!