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, e.g. [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()) {