簡體   English   中英

逆數組(Java)//逆數組(Java)

[英]Inverse array (Java) // Invertir array (Java)

我可以通過遞歸方法對數組求逆,例如:array = {1,2,3,4,5} arrayresult = {5,4,3,2,1},但我的結果是同一個數組,我不知道為什么,請幫幫我。

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

}類main是數組

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

}}

提示:您正在交換元素-這意味着您只需要遍歷數組的一半 ...

你需要改變

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

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

否則,將前半部分反轉,然后將其反轉回來。

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

測試

zero elements:  [] --> []

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM