Recursively reverse an array

Reply

Join Date: Nov 2008
Posts: 1
Reputation: superbob7 is an unknown quantity at this point 
Solved Threads: 0
superbob7 superbob7 is offline Offline
Newbie Poster

Recursively reverse an array

 
0
  #1
Nov 19th, 2008
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.

  1. public class arraybackwards {
  2. public static void main(String[] args){
  3. int[] bob = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18};
  4. int[] toSend = new int[bob.length];
  5. int index = 0;
  6. bob = backwards(bob,toSend,bob.length, index);
  7. for(int i = 0; i < bob.length; i++){
  8. System.out.print(bob[i] + " ");
  9. }
  10.  
  11. }
  12.  
  13. public static int[] backwards(int[] arg, int[] toSend, int length, int index){
  14.  
  15.  
  16. if (length > 0)
  17. {
  18. int bob = arg[length-1];
  19. toSend[index] = bob;
  20. backwards(arg,toSend,length-1,++index);
  21.  
  22. }
  23.  
  24. return toSend;
  25.  
  26. }
  27. }
Reply With Quote Quick reply to this message  
Join Date: Dec 2004
Posts: 4,188
Reputation: peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of 
Solved Threads: 482
Moderator
Featured Poster
peter_budo's Avatar
peter_budo peter_budo is online now Online
Code tags enforcer

Re: Recursively reverse an array

 
0
  #2
Nov 19th, 2008
  1. public class ArrayReverse {
  2. public static void main(String[] args){
  3. int[] bob = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18};
  4. int[] newBob = new int[bob.length];
  5. newBob = reverseArray(bob);
  6. for(int i = 0; i < bob.length; i++){
  7. System.out.print(newBob[i] + " ");
  8. }
  9. }
  10.  
  11. public static int[] reverseArray(int[] arr){
  12. int[] arrReverse = new int[arr.length];
  13. int p = 0;
  14. for(int i = arr.length -1; i >-1; i--)
  15. {
  16. arrReverse[p] = arr[i];
  17. p++;
  18. }
  19. return arrReverse;
  20. }
  21. }
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
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Java Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC