Bubblesort在Java上不起作用,元素未交换

时间:2019-05-05 22:41:17

标签: java bubble-sort

我的测试代码如下:

import java.util.Arrays;

class Scratch {
    public static void main(String[] args) {
        int[] list = {5,4,1,651,68,7,486,49,3,4,6};
        bubblesort(list);
        System.out.println(Arrays.toString(list));

    }
    private static void bubblesort(int[] a) {
        int[] list = a;
        for (int i = 0; i < list.length - 1; i++) {
            for (int j = 0; j < list.length - i - 1; j++) {
                if (list[j] > list[j + 1]) {
                    int temp = list[j];
                    list[j] = list[j + 1];
                    list[j] = temp;
                }
            }
        }
    }
}

输出仍然是:

[5, 4, 1, 651, 68, 7, 486, 49, 3, 4, 6]

我进行了多次测试,例如使用return或设置另一个变量。但是我的方法都不起作用...

3 个答案:

答案 0 :(得分:2)

简而言之,我认为您的问题是连续两次设置 list[j]

您应该在 list[j+1] = temp 语句的最后一行设置 if

答案 1 :(得分:0)

int temp = list[j]; list[j] = list[j + 1]; list[j+1] = temp;

您要为temp分配list [j]值,并为list [j]重新分配temp值,因此输出中没有变化。因此,那里没有交换发生。

答案 2 :(得分:0)

Replace the if block with this one

if (list[j] > list[j + 1]) {
   int temp = list[j];
   list[j] = list[j + 1];
   list[j+1] = temp;
}
相关问题