| | |
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 |
addball android applet application apps array automation awt bidirectional binary birt bluetooth businessintelligence busy_handler(null) button card class classes client code collision columns component constructor crashcourse css database designadrawingapplicationusingjavajslider draw eclipse ee error eventlistener exception expand fractal free game givemetehcodez graphics gui guidancer html ide image integration intellij j2me java javadoc javafx javamicroeditionuseofmotionsensor javaprojects jme jni jpanel jtree julia jvm linux loan loop method migrate mobile mobiledevelopmentcreatejar myaggfun netbeans newbie oracle phone physics plazmic print problem program programming project radio scanner server service set sharepoint smart sms smsspam software sql subclass support swing textfield threads tree trolltech ubuntu unlimited utility windows






