简体   繁体   English

我怎样才能使 java 中的这个冒泡排序工作

[英]how can i make this bubblesort in java work

int[] array = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

        for (int x = 0; x < array.length; x++) {
            System.out.print("[" + array[x] + "] ");
        }

        for (int x = 0; x < array.length; x++) {

            for (int y = 0; y < x; y++) {

                if (array[y] > array[x]) {

                    int temp = array[x];
                    array[y] = array[x];
                    array[x] = temp;
                }

            }
        }
        System.out.println();
        for (int x = 0; x < array.length; x++) {
            System.out.print("[" + array[x] + "] ");

        }

can someone tell me why this bubblesort is not working?有人能告诉我为什么这个冒泡排序不起作用吗? cant find my mistake.找不到我的错误。

help would be appreciated帮助将不胜感激

Your understanding of bubblesort seems okay.您对冒泡排序的理解似乎还可以。 The issue is in your swap functionality, you can tell this because you are duplicating values.问题在于您的交换功能,您可以告诉这一点,因为您正在重复值。 You are setting the temp variable to array[x] and then setting array[y] to array[x] then setting array[x] to temp.您将 temp 变量设置为 array[x],然后将 array[y] 设置为 array[x],然后将 array[x] 设置为 temp。 So in the end array[x] = array[x] and array[y] = array[x].所以最后 array[x] = array[x] 和 array[y] = array[x]。 The simple fix is changing your temp to be temp = array[y]简单的解决方法是将您的 temp 更改为 temp = array[y]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM