0

I'm trying to write a recursive method that takes an integer array and copies alternating elements into two separate arrays until there are no elements left to split.

For example:

[0 1 2 3 4 5 6 7 8 9]  
...  

[0 2 4 6 8]
[1 3 5 7 9] / 
[0 4 8]
[2 6] / 
[0 8]
[4] / 
[0]
[8] / 
[2]
[6] / 
[1 5 9]
[3 7] / 
[1 9]
[5] / 
[1]
[9] / 
[3]
[7] 

So far I have been able to split the initial array, but my recursion won't terminate. Any suggestions?

Here is the method's code:

public static void halve(int[] a, int x)
{
    for (int i = 0; i < x; i = i + 2)
    {
        xList[i/2] = i;
        yList[i/2] = i + 1;
    }

    printList(xList);
    printList(yList);

    if (x-1 > 2)
        halve(xList, xList.length-1);
    else if (x-1 > 2)
        halve(yList, yList.length-1);
}
1
  • 1
    What is xList and yList? Commented Sep 15, 2014 at 22:20

2 Answers 2

2

It seems that xList and yList are int[]s. In that case xList.length-1 and yList.length-1 always return the same numbers so argument x for halve is always greater than 3 and your recursion never stops.

This is not to mention other problems like:

  1. You are filling xList and yList with indices instead of elements of a.
  2. The i + 1 is going out of bounds if x is odd.
  3. The same conditions for if and else if - you definitely meant something else.
Sign up to request clarification or add additional context in comments.

Comments

0

Ok this code outputs the results you wanted:

public class Recursive {
private static int[] array = {0,1,2,3,4,5,6,7,8,9};

public static void main(String[] args){
    half(array);
}
public static void half(int[] array){
    int[] evenarray,oddarray;
    if(array.length%2==1){
        evenarray = new int [array.length/2+1];
        oddarray = new int[array.length/2];
    }else{
        evenarray = new int [array.length/2];
        oddarray = new int[array.length/2];
    }
    for (int i=0; i<array.length; i++){
        if(i%2==0){
            evenarray[i/2]=array[i];
        }else{
            oddarray[i/2]=array[i];
        }
    }
    for(int i = 0; i<evenarray.length; i++){
        System.out.print(evenarray[i]);
    }
    System.out.println();
    for(int i = 0; i<oddarray.length; i++){
        System.out.print(oddarray[i]);
    }
    System.out.println();
    if(evenarray.length>1)half(evenarray);
    if(oddarray.length>1)half(oddarray);

}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.