首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >逆数组(Java) //反向数组(Java)

逆数组(Java) //反向数组(Java)
EN

Stack Overflow用户
提问于 2016-03-11 23:38:34
回答 3查看 1.1K关注 0票数 0

我可以通过递归方法逆数组,例如: array={1,2,3,4,5} arrayresult={5,4,3,2,1}但我的结果是相同的数组,我不知道为什么,请帮帮我。

代码语言:javascript
复制
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,The是数组

代码语言:javascript
复制
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);

}}

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-03-11 23:43:46

提示:您正在交换元素--这意味着您只需要遍历数组的.

票数 2
EN

Stack Overflow用户

发布于 2016-03-11 23:44:52

你需要改变

代码语言:javascript
复制
public static int arrayReverse(int [] array, int indice, int pos){
    if(indice>=0 && pos<array.length){

到某种程度上

代码语言:javascript
复制
public static int arrayReverse(int [] array, int indice, int pos){
    if(indice>=0 && pos<(array.length/2)){

否则你就倒转上半场,然后倒回去。

票数 1
EN

Stack Overflow用户

发布于 2016-03-11 23:51:57

代码语言:javascript
复制
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);
    }
}

测试

代码语言:javascript
复制
zero elements:  [] --> []

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

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

odd# elements:  [1,2,3] --> [3,2,1]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35951842

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档