mirror of
https://gitlab.uni-marburg.de/langbeid/powersort.git
synced 2025-01-21 19:50:35 +01:00
add bubblesort
This commit is contained in:
parent
a945a3278e
commit
3560f261a3
@ -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;
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user