【发布时间】:2016-07-24 21:07:33
【问题描述】:
所以我正在研究一个以递归为重点的教科书练习题,我已经完成了一半。我想出了两个函数,它们将一个数组中的元素递归复制到另一个数组中,但我有点卡在我的 reverseArray3 函数上。
reverseArray3 应该将包含从索引 i 到索引 j 的元素组成的子数组 X[i,...j] 反转。我知道它应该通过交换位置 i 和 j 的元素然后在子数组 X[i+1,...,j-1] 上从索引 i+1 和 j-1 递归调用自身来做到这一点。 我试图查找类似于我的问题,但没有运气。任何帮助
class Recursion {
static void reverseArray1(int[] X, int n, int[] Y) {
if(n < 1)
return;
Y[Y.length-n] = X[n-1];
reverseArray1(X, n-1, Y);
}
static void reverseArray2(int[] X, int n, int[] Y) {
if(n < 1)
return;
Y[n-1] = X[X.length-n];
reverseArray2(X, n-1, Y);
}
static void reverseArray3(int[] X, int i, int j) {
//Where I'm stuck
}
public static void main(String[] args) {
int[] A = {-1, 2, 3, 12, 9, 2, -5, -2, 8, 5, 7};
int[] B = new int[A.length];
int[] C = new int[A.length];
for(int x: A) System.out.print(x+" ");
System.out.println();
reverseArray1(A, A.length, B);
for(int x: B) System.out.print(x+" ");
System.out.println();
reverseArray2(A, A.length, C);
for(int x: C) System.out.print(x+" ");
System.out.println();
reverseArray3(A, 0, A.length-1);
for(int x: A) System.out.println(x+" ");
System.out.println();
}
}
下面是输出的样子:
1 2 6 12 9 2 -5 -2 8 5 7
7 5 8 -2 -5 2 9 12 6 2 -1
7 5 8 -2 -5 2 9 12 6 2 -1
7 5 8 -2 -5 2 9 12 6 2 -1
【问题讨论】:
标签: java arrays recursion data-structures reverse