DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   Java (http://www.daniweb.com/forums/forum9.html)
-   -   Recursively reverse an array (http://www.daniweb.com/forums/thread158322.html)

superbob7 Nov 19th, 2008 11:08 am
Recursively reverse an array
 
I was messing around trying to figure this out and came up with this. This works but I'm looking for a more elegant recursive solution. Can anyone think of one? I couldn't find anything with google. Oh and sorry for the stupid variable names.

public class arraybackwards {
    public static void main(String[] args){
        int[] bob = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18};
        int[] toSend = new int[bob.length];
        int index = 0;
        bob = backwards(bob,toSend,bob.length, index);
        for(int i = 0; i < bob.length; i++){
            System.out.print(bob[i] + " ");
        }
       
    }
   
    public static int[] backwards(int[] arg, int[] toSend, int length, int index){
       
       
        if (length > 0)
        {
                int bob = arg[length-1];
                toSend[index] = bob;
                backwards(arg,toSend,length-1,++index);
               
        }
       
        return toSend;

    }
}

peter_budo Nov 19th, 2008 11:59 am
Re: Recursively reverse an array
 
public class ArrayReverse {
    public static void main(String[] args){
        int[] bob = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18};
        int[] newBob = new int[bob.length];
        newBob = reverseArray(bob);
        for(int i = 0; i < bob.length; i++){
            System.out.print(newBob[i] + " ");
        }       
    }
   
    public static int[] reverseArray(int[] arr){
        int[] arrReverse = new int[arr.length];
        int p = 0;   
        for(int i = arr.length -1; i >-1; i--)
        {
                arrReverse[p] = arr[i];
                p++;
        }       
        return arrReverse;
    }
}


All times are GMT -4. The time now is 3:15 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC