[英]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. 在第二种方法(当前为空白)中,将元素放入新的out
数组中时,需要在索引index
和in.length - index - 1
处交换它们。 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. 然后当然要对index + 1
进行同样的操作,除非您位于数组的中间,在这种情况下您可以完成并可以返回。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.