From 3560f261a3ad33edab0144332d084e71b528a577 Mon Sep 17 00:00:00 2001 From: Daniel Langbein Date: Tue, 10 Dec 2024 16:54:36 +0000 Subject: [PATCH] add bubblesort --- .../powersort/sort/BubbleSort.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 app/src/main/java/de/uni_marburg/powersort/sort/BubbleSort.java diff --git a/app/src/main/java/de/uni_marburg/powersort/sort/BubbleSort.java b/app/src/main/java/de/uni_marburg/powersort/sort/BubbleSort.java new file mode 100644 index 0000000..c70c2f5 --- /dev/null +++ b/app/src/main/java/de/uni_marburg/powersort/sort/BubbleSort.java @@ -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 void sort(final T[] list, Comparator 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 void sortGreaterThan2(final T[] list, Comparator 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; + } +}