0

I can inverse array by recursive method, for example: array={1,2,3,4,5} arrayresult={5,4,3,2,1} but my result is the same array, I don't know why, help me please.

public class Recursion {
public static int arrayReverse(int [] array, int indice, int pos){
    if(indice>=0 && pos<array.length){
        int tmp = array[pos];
        array[pos]=array[indice];
        array[indice]=tmp;
        arrayReverse(array, indice-1, pos+1);
    }
    return array[array.length-1];
}

public static void arrayReverse(int [] array){
    arrayReverse(array, array.length-1, 0);
}

} The class main, were is the arrays

import java.util.Arrays;

public class Main {
/**
 * Prueba el método Recursion.arrayReverse
 * @param input - array a tratar
 * @param expected - resultado esperado
 */
static void test(int[] input, int[] expected) {
    // Se informa del caso que se está probando
    System.out.println("probando: arrayReverse(" + Arrays.toString(input) + ")");

    // Llamada al método a probar
    Recursion.arrayReverse(input);

    // Comprobación de los resultados
    if (!Arrays.equals(input, expected)) {
        System.out.print(">> Resultado erróneo, deberia ser: " + Arrays.toString(expected) + "");
        System.out.println(" y es: " + Arrays.toString(input) + "");
    } else {
        System.out.println(">> Resultado correcto: " + Arrays.toString(input) + "");
    }        
}

/**
 * Invoca a test para realizar múltiples pruebas
 * @param args
 */
public static void main(String[] args) {
    int[] v1 = {1, 2, 3, 4, 5};
    int[] v2 = {5, 4, 3, 2, 1};
    test(v1, v2);

} }

3 Answers 3

2

Hint: You are swapping elements - it means that you only need to iterate through half of the array...

Sign up to request clarification or add additional context in comments.

Comments

1

You need to change

public static int arrayReverse(int [] array, int indice, int pos){
    if(indice>=0 && pos<array.length){

to something like

public static int arrayReverse(int [] array, int indice, int pos){
    if(indice>=0 && pos<(array.length/2)){

Otherwise you reverse the first half, and then reverse it back.

Comments

1
static class Recursion {

    private static void arrayReverse(int[] array, int indice, int pos) {
        if (indice > pos ) { // change
            int tmp = array[pos];
            array[pos] = array[indice];
            array[indice] = tmp;
            arrayReverse(array, indice - 1, pos + 1);
        }           
    }

    public static void arrayReverse(int[] array) {
        arrayReverse(array, array.length - 1, 0);
    }
}

Tests

zero elements:  [] --> []

single element: [1] --> [1]

even# elements: [1,2] --> [2,1]

odd# elements:  [1,2,3] --> [3,2,1]

Comments

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.