The question is somewhat unclear, but I assume that the "sub-array" is half the arr object.
Lame way to do it like this
public int sum(int[] arr){ int total = 0; for(int index : arr){ total += index; } return total; } public void foo(){ int arr[] = {0,-1,2,-3,5,9,-5,10}; int subArr1[] = new int[(arr.length/2)]; int subArr2[] = new int[(arr.length/2)]; for(int i = 0; i < arr.length/2; i++){
I think this may not work if arr contains an odd number of elements.
If you want access to a higher level of support, convert primvate arrays to a List object
List<Integer> list = Arrays.asList(arr);
Thus, you have access to the functionality of the collection object.
Also, if you have the time, look at a higher order functional called shortening. You will need a library that supports functional programming. Guava or lambdaJ may have a reduction method. I know that apache-commons is missing one if you don't want to hack it together.
Dan
source share