2016-04-05 14 views
2

Also arbeite ich an einem Lehrbuch Praxis Problem mit Schwerpunkt auf Rekursion, die ich bin halb da. Ich habe zwei Funktionen gefunden, die rekursiv das Element in ein Array in ein anderes kopieren, aber ich bin irgendwie auf meiner reverseArray3-Funktion fest.Rekursive Funktion, die das Subarray X [i, ..., j] umkehrt. Elemente von Index i bis j einschließlich

reverseArray3 sollte das Subarray X [i, ... j] umkehren, das aus diesen Elementen von Index i bis einschließlich Index j besteht. Ich weiß, es sollte dies tun, indem ich Elemente an Position i vertausche und j dann rekursiv auf Unterfeld X [i + 1, ..., j-1] von Index i + 1 und j-1 aus rufe. Ich habe versucht, eine ähnliche Frage wie meine aufzuschlagen, aber kein Glück. Jede Hilfe

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

unten ist, wie die Ausgabe aussehen sollte:

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 

Antwort

2

Ich schlage vor, diese:

static void reverseArray3(int[] X, int i, int j) { 
    if(i>=j) 
     return; 
    int a=X[j]; 
    X[j]=X[i]; 
    X[i]=a; 
    reverseArray3(X,i+1,j-1); 
} 

Ich hoffe, es hilft.

+0

Danke, hab es! – HPotter

Verwandte Themen