1

Create and return a new array that is a reversed copy of the array passed as a parameter.

The code I have is the following. I am stuck on the algorithm? This was an exam question but the exam is now over.

import java.util.*;

public class Q4_ArrayReverse
{
   public static String[] reverse( String[] in )
   {
      String[] out = new String[ in.length ];
      reverse( in, out, 0 );
      return out;
   }
   ///////////////////////////////////////////////////////////
   //
   // Given an input array, an output array and an index,
   //    copy the element at the index offset of the input array
   //    to the appropriate reversed position in the output array.
   //    i.e. in[ 0 ] -> out[ n - 1 ]
   //         in[ 1 ] => out[ n - 2 ]
   //            etc.
   //    After doing the copy for index, recurse for index + 1
   //    Be sure to quit when you get to the end of the array.
   //
   //////////////////////////////////////////////////////////
   static void reverse( String[] in, String[] out, int index )
   {







   }
2
  • Well, break it down into its components. In recursion, there always needs to be a terminating condition. Commented Apr 25, 2013 at 23:36
  • 1
    Q4_ArrayReverse is a hateful class name that doesn't match the Java naming convention. Commented Apr 25, 2013 at 23:37

1 Answer 1

1

In your second (currently blank) method, you will want to swap elements at indexes index and in.length - index - 1 when putting them in the new out array. Then of course you want to do the same for index + 1, unless you are at the middle of the array in which case you're finished and can return.

if (index == array.length / 2)  // i.e. 1 position past the middle
    return

out[index] = in[in.length - index - 1];
out[in.length - index - 1] = in[index];

reverse(in, out, index+1);
Sign up to request clarification or add additional context in comments.

1 Comment

if (index == in.length) // i.e. 1 position past the middle return; out[out.length - (index + 1)] = in[index]; reverse(in, out, index+1); It turns out this was enough, not sure why array.length/2 is not necessary.

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.