add bubblesort

This commit is contained in:
Daniel Langbein 2024-12-10 16:54:36 +00:00
parent a945a3278e
commit 3560f261a3
Signed by: langfingaz
GPG Key ID: 6C47C753F0823002

View File

@ -0,0 +1,49 @@
package de.uni_marburg.powersort.sort;
import java.util.Comparator;
/**
* This utility class provides a method
* to sort a list of integers in ascending order.
*/
public final class BubbleSort {
private BubbleSort() {
}
/**
* Algorithm form lecture with addition of early exit if no more swaps occur.
*/
public static <T> void sort(final T[] list, Comparator<T> c) {
// Only lists with 2 or more elements need to be sorted.
final boolean greaterThan2 = list.length >= 2;
if (greaterThan2) {
sortGreaterThan2(list, c);
}
}
/**
* Helper.
*
* @param list List with >= 2 elements.
*/
private static <T> void sortGreaterThan2(final T[] list, Comparator<T> c) {
for (int i = list.length; i >= 1; i--) {
boolean swapped = false;
for (int j = list.length - 2; j >= 0; j--) {
if (c.compare(list[j], list[j + 1]) > 0) {
swap(list, j, j + 1);
swapped = true;
}
}
if (!swapped) {
return;
}
}
}
private static void swap(final Object[] list, final int idx1, final int idx2) {
final Object tmp = list[idx1];
list[idx1] = list[idx2];
list[idx2] = tmp;
}
}