简体   繁体   中英

splitting array using recursion java

I am trying to spit an int array and add up the elements but im getting errors. Here is my code. I can't figure it out.

int arraySize = 10;
int[] numsToSum = new int[arraySize];
for (int i = 0; i < arraySize; i++)
{
    numsToSum[i] = i * 3;
    System.out.println(numsToSum[i]);
}
int sum3 = sumArray3(numsToSum, 0, arraySize - 1);
System.out.println(sum3);

 public static int sumArray3(int [] array, int start, int end)
 {
    int results = 0;
    int mid = (start + end)/2;
    if(array.length > 0)
    {

        results += sumArray3(array, start + 1, mid) + sumArray3(array, mid +1,   end);

    }
    return results;

You don't have a recursion termination condition, in this case i'd assume you want to check if the start and end counters for the array are the same. Check the code below.

class StackOv {

    public static void main(String[] args) {
        int arraySize = 10;
        int[] numsToSum = new int[arraySize];
        for (int i = 0; i < arraySize; i++)
        {
                numsToSum[i] = i * 3;
                System.out.println(numsToSum[i]);
        }
        int sum3 = sumArray3(numsToSum, 0, arraySize - 1);
        System.out.println(sum3);
    }

    public static int sumArray3(int [] array, int start, int end)
    {
        int results = 0;
        if(start == end)
            return array[start];
        int mid = (start + end)/2;
        if(array.length > 0) {
                results += sumArray3(array, start, mid) + sumArray3(array, mid +1, end);
        }
        return results;
    }
}

It looks like you don't have a "base-case", where you return a solid value. Your function as-is will always return 0 .

At a guess, I would say you should start by changing it so that you check whether start+1 <= end and if so, returning your current value; if not returning the value at that index, with an else :

else {
  results = array[start];
}

I finally figured it out. Thanks for your help. I didn't have a base like you said.

public static int sumArray3(int [] array, int start, int end)
{
    int results = 0;
    int mid = (start + end)/2;
    if(start < end)
    {
        results += sumArray3(array, start, mid) + sumArray3(array, mid +1, end);

    }
    else
        results = array[start];
    return results;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM