简体   繁体   中英

Collections.sort & Bubble sort

Iam using two different ways of sorting Results in an ArrayList. The first way is Collections.sort which works just fine so no problem there. The other is the sorting algoritm Bubblesort (I know its ineffective, using in study purposes) I have collections sort to sort results with the biggest values at 0 and second biggest at 1 etc. I want my bubble sort algoritm so sort the other way around, with the smallet values at 0 etc. As mentioned, collections sort works fine but my bubble sort doesnt sort them the way I want to.

Is it my method or the loop which is wrong?

private void sort(boolean resultComparison, ArrayList<Result> list) {
    if (resultComparison= false) {
        boolean moved;
        do {
            moved= false;
            for (int i = 1; i < list.size(); i++) {
                Result in = list.get(i - 1);
                Result de = list.get(i);
                if (in.value() < de.value()) {
                    list.set(i - 1, de);
                    list.set(i, in);
                    moved= true;
                }
            }
        } while (moved);
    } else {
        Collections.sort(list);
    }
}

The boolean resultComparison is an attribute each instance of my class has, false should print out results small to big.

Currently, your bubble sort is sorting in a descending order, with the largest value at the 0 index in the list. This is because you are swapping two consecutive values if the first one is less than the second, eg [4, 5] => 4 < 5 => [5, 4].

Reverse the comparison, so that you swap the two consecutive values if the first one is greater than the second. Change

if (in.value() < de.value()) {

to

if (in.value() > de.value()) {

Your code looks pretty much correct to me. I tried a roughly equivalent test:

List<Integer> list = Arrays.asList(6, 3, 1, 9, 0);
boolean moved;
do {
    moved = false;
    for (int i = 1; i < list.size(); i++) {
        if (list.get(i - 1) > list.get(i)) {
            Collections.swap(list, i - 1, i);
            moved = true;
        }
    }
 } while (moved);
 System.out.println(list);

This worked exactly as expected. I suspect your issues are in your Result class or comparison testing. Can you post some output showing the error.

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