| | |
Recursively reverse an array
![]() |
•
•
Join Date: Nov 2008
Posts: 1
Reputation:
Solved Threads: 0
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.
java Syntax (Toggle Plain Text)
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; } }
Java Syntax (Toggle Plain Text)
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; } }
Learn to see in another's calamity the ills which you should avoid.
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
![]() |
Similar Threads
- Dont know where to go next. (Java)
Other Threads in the Java Forum
- Previous Thread: Parse String
- Next Thread: Play a wav. file
| Thread Tools | Search this Thread |
911 actionlistener addressbook android api append applet application array arrays automation binary blackberry block bluetooth character chat class client code component consumer csv database desktop developmenthelp eclipse error fractal ftp game givemetehcodez graphics gui html ide image integer j2me j2seprojects japplet java javaarraylist javac javaee javaprojects jni jpanel julia lego linked linux list loops mac map method methods mobile netbeans newbie number objects online oriented panel printf problem program programming project projects properties recursion replaydirector reporting researchinmotion rotatetext rsa scanner se server set singleton sms sort sql string swing test textfields threads time title tree tutorial-sample ubuntu update windows working






