简体   繁体   中英

Recursively reverse an array of strings

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 )
   {







   }

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM