简体   繁体   中英

Why when I reverse the comparison sign in my bubble sort algorithm does the resulting sorting list not reverse?

Java Code:

    public static NHLList bubbleSort(NHLList players) {
        for (int i = 0; i < players.size(); i++) {
            for (int j = 0; j < players.size()-1; j++) {
                if (players.get(j).getPoints() < players.get(j+1).getPoints()) {
                    PlayerRecord tempPlayer = players.get(j);
                    players.set(players.get(j+1), j);
                    players.set(tempPlayer, j+1);
                }
            }
        }
        return players;
    }

If I change j < ... to j > ... the resulting list is not the previous list inverted, though I would assume it should be. All it's doing is reading numbers.

rolls sleeves up

You're inverting the sign on the wrong line.

As others have pointed out, please specify which line you are editing. If you are editing the right line then you may be unhappy to hear that this is not actually implementing BubbleSort .

You are actually performing a complete scan of the list n times which may, under some circumstances, result in a sorted list but is not actually what BubbleSort is all about. I would suggest you study your code and try to work out for yourself why your loop-counter i is never being referred to in the code (apart from in the loop control).

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