简体   繁体   中英

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. So in the end array[x] = array[x] and array[y] = array[x]. The simple fix is changing your temp to be temp = array[y]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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