improve QuickSort

This commit is contained in:
Daniel Langbein 2024-12-17 19:18:16 +00:00
parent 6d25796bac
commit 0b483c32f3
Signed by: langfingaz
GPG Key ID: 6C47C753F0823002
2 changed files with 17 additions and 15 deletions

View File

@ -1,40 +1,42 @@
package de.uni_marburg.powersort.sort; package de.uni_marburg.powersort.sort;
import java.util.Comparator;
public class QuickSort { public class QuickSort {
/** /**
* Based on https://www.baeldung.com/java-quicksort * Based on https://www.baeldung.com/java-quicksort
*/ */
public static void sort(Integer[] arr) { public static <T> void sort(final T[] arr, Comparator<T> c) {
quickSort(arr, 0, arr.length-1); quickSort(arr, c, 0, arr.length - 1);
} }
private static void quickSort(Integer[] arr, int begin, int end) { private static <T> void quickSort(T[] arr, Comparator<T> c, int begin, int end) {
if (begin < end) { if (begin < end) {
int partitionIndex = partition(arr, begin, end); int partitionIndex = partition(arr, c, begin, end);
quickSort(arr, begin, partitionIndex-1); quickSort(arr, c, begin, partitionIndex - 1);
quickSort(arr, partitionIndex+1, end); quickSort(arr, c, partitionIndex + 1, end);
} }
} }
private static int partition(Integer[] arr, int begin, int end) { private static <T> int partition(T[] arr, Comparator<T> c, int begin, int end) {
int pivot = arr[end]; T pivot = arr[end];
int i = (begin-1); int i = (begin - 1);
for (int j = begin; j < end; j++) { for (int j = begin; j < end; j++) {
if (arr[j] <= pivot) { if (c.compare(arr[j], pivot) <= 0) {
i++; i++;
int swapTemp = arr[i]; T swapTemp = arr[i];
arr[i] = arr[j]; arr[i] = arr[j];
arr[j] = swapTemp; arr[j] = swapTemp;
} }
} }
int swapTemp = arr[i+1]; T swapTemp = arr[i + 1];
arr[i+1] = arr[end]; arr[i + 1] = arr[end];
arr[end] = swapTemp; arr[end] = swapTemp;
return i+1; return i + 1;
} }
} }

View File

@ -14,7 +14,7 @@ public enum SortEnum {
public SortImpl getSortImpl() { public SortImpl getSortImpl() {
return switch (this) { return switch (this) {
case BUBBLE_SORT -> array -> BubbleSort.sort(array, NaturalOrder.INSTANCE); case BUBBLE_SORT -> array -> BubbleSort.sort(array, NaturalOrder.INSTANCE);
case QUICK_SORT -> array -> QuickSort.sort((Integer[]) array); // TODO rm cast case QUICK_SORT -> array -> QuickSort.sort(array, NaturalOrder.INSTANCE);
case MERGE_SORT -> array -> MergeSort.legacyMergeSort(array, NaturalOrder.INSTANCE); case MERGE_SORT -> array -> MergeSort.legacyMergeSort(array, NaturalOrder.INSTANCE);
case TIM_SORT -> array -> TimSort.sort(array, 0, array.length, NaturalOrder.INSTANCE, null, 0, 0); case TIM_SORT -> array -> TimSort.sort(array, 0, array.length, NaturalOrder.INSTANCE, null, 0, 0);
case FINN_SORT -> array -> FinnSort.sort(array, NaturalOrder.INSTANCE); case FINN_SORT -> array -> FinnSort.sort(array, NaturalOrder.INSTANCE);