mirror of
https://gitlab.uni-marburg.de/langbeid/powersort.git
synced 2025-01-21 19:50:35 +01:00
improve QuickSort
This commit is contained in:
parent
6d25796bac
commit
0b483c32f3
@ -1,37 +1,39 @@
|
||||
package de.uni_marburg.powersort.sort;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
public class QuickSort {
|
||||
/**
|
||||
* Based on https://www.baeldung.com/java-quicksort
|
||||
*/
|
||||
public static void sort(Integer[] arr) {
|
||||
quickSort(arr, 0, arr.length-1);
|
||||
public static <T> void sort(final T[] arr, Comparator<T> c) {
|
||||
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) {
|
||||
int partitionIndex = partition(arr, begin, end);
|
||||
int partitionIndex = partition(arr, c, begin, end);
|
||||
|
||||
quickSort(arr, begin, partitionIndex-1);
|
||||
quickSort(arr, partitionIndex+1, end);
|
||||
quickSort(arr, c, begin, partitionIndex - 1);
|
||||
quickSort(arr, c, partitionIndex + 1, end);
|
||||
}
|
||||
}
|
||||
|
||||
private static int partition(Integer[] arr, int begin, int end) {
|
||||
int pivot = arr[end];
|
||||
private static <T> int partition(T[] arr, Comparator<T> c, int begin, int end) {
|
||||
T pivot = arr[end];
|
||||
int i = (begin - 1);
|
||||
|
||||
for (int j = begin; j < end; j++) {
|
||||
if (arr[j] <= pivot) {
|
||||
if (c.compare(arr[j], pivot) <= 0) {
|
||||
i++;
|
||||
|
||||
int swapTemp = arr[i];
|
||||
T swapTemp = arr[i];
|
||||
arr[i] = arr[j];
|
||||
arr[j] = swapTemp;
|
||||
}
|
||||
}
|
||||
|
||||
int swapTemp = arr[i+1];
|
||||
T swapTemp = arr[i + 1];
|
||||
arr[i + 1] = arr[end];
|
||||
arr[end] = swapTemp;
|
||||
|
||||
|
@ -14,7 +14,7 @@ public enum SortEnum {
|
||||
public SortImpl getSortImpl() {
|
||||
return switch (this) {
|
||||
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 TIM_SORT -> array -> TimSort.sort(array, 0, array.length, NaturalOrder.INSTANCE, null, 0, 0);
|
||||
case FINN_SORT -> array -> FinnSort.sort(array, NaturalOrder.INSTANCE);
|
||||
|
Loading…
x
Reference in New Issue
Block a user