Java:为什么我的递归排序方法不起作用?

问题描述 投票:0回答:3

我在下面写的递归排序方法在使用典型的sout时打印地址(“[I @ 7852e922”),我相信这与我在sort()中的返回有关。我试图让方法无效,但这似乎不起作用,因为我需要删除返回。但是,当我最终用这个混乱替换它时,它打印出未排序的数组,所以结果我的方法是无效的:

System.out.println(Arrays.toString(sort(array2, array2.length-1)));

由于我的先决条件训练不佳,并且在写这篇文章前10分钟学会了典型的冒泡排序,因此我在编程/递归方面遇到了严重的困难。这是我的整个测试程序:

TL; DR:我的排序方法有什么问题,应该如何打印?

public static void main(String[] args) {
    int array2[] = new int[]{1, 3, 5, 2, 4};
    System.out.println(Arrays.toString(sort(array2, array2.length-1)));
}

    static public int[] sort(int[] array, int n) {
    int i = array[n];
    int j = i-1;
    int temp;
    if(n == 0) {
        return array;
    } else if(i < j) {
        temp = i;
        i = j;
        j = temp;
        return sort(array, n - 1);
    } else {
        return sort(array, n - 1);
    }
}

谢谢!

编辑:经过反馈,这就是我留下的。测试工作完美,打印我的数组排序。我发现在查看代码的时间过长时,我倾向于将我与x [i]混淆。但是,我仍然无法避免使用Arrays.toString()或更改为void sort()。如果必须,我会坚持这一点。话虽如此,我感谢任何进一步的帮助。

public static void main(String[] args) {
    int array2[] = new int[]{1, 3, 5, 2, 4};
    System.out.println(Arrays.toString(sort(array2, array2.length - 1)));
}

static public int[] sort(int[] array, int lastIndex) {
    int j = lastIndex - 1;
    int temp;
    if (lastIndex == 0) {
        return array;
    } else if (array[lastIndex] < array[j]) {
        temp = array[lastIndex];
        array[lastIndex] = array[j];
        array[j] = temp;
        return sort(array, lastIndex - 1);
    } else if (array[lastIndex] > array[j]) {
        return sort(array, lastIndex - 1);
    }
    return array;
}
java arrays sorting recursion bubble-sort
3个回答
0
投票

尽管您的代码错误,但您的代码打印出来并不错。

您不需要使用返回值,但在将其再次分配给变量时没有任何区别。

查看https://www.geeksforgeeks.org/recursive-bubble-sort/的工作递归示例。


0
投票

这是你的答案。我在代码中内联了注释。希望能帮助到你。

    private static int[] sort(int[] array, int lastIndex) {
    if(lastIndex<1) { //If array has only 1 element to be sorted then return array as is.
        return array;
    }
    //move the largest number in the array to the last index of the array;
    for(int i=0;i<array.length-1;i++) {
        if(array[i] > array[i+1]) {
            //swap
            int temp = array[i];
            array[i] = array[i+1];
            array[i+1] = temp;
        }
    }
    // now we know lastIndex element is highest, sort other elements by decrementing lastIndex
    return sort(array, lastIndex-1);
}

0
投票

你这里有很多问题。首先,比较索引(i和j是索引,它们告诉你数组中成员的位置)。你解决了我的比较值,如下所示:

else if(array[j] < array[i]){
     temp = array[i];
     array[i] = array[j];
     array[j] = temp;   }

其次,这样编写它只会执行一次冒泡排序迭代,所以你只能确定最低值会出现在数组的开头(如果你知道冒泡排序是如何工作的)。要解决这个问题,你必须再添加一层递归调用,但这次你只调用n - 1个数组元素,因为你确定了最低值。

解决此问题而不更改排序方法的另一种方法是调用for循环并执行n次排序方法。

© www.soinside.com 2019 - 2024. All rights reserved.