QuicksortTask.java
/*
* Copyright 2024 Hochschule Luzern Informatik.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.hslu.exercises.sw11.ex2.quicksort;
import java.util.concurrent.RecursiveAction;
/**
* Codevorlage zu RecursiveAction für die Sortierung eines int-Arrays.
*/
public final class QuicksortTask extends RecursiveAction {
private final int threshold;
private final int[] array;
private final int min;
private final int max;
/**
* Erzeugt einen Array-Sortier Task.
*
* @param array Interger-Array.
*/
public QuicksortTask(int[] array, final int threshold) {
this(array, 0, array.length - 1, threshold);
}
private QuicksortTask(final int[] array, final int min, final int max, final int threshold) {
this.array = array;
this.min = min;
this.max = max;
this.threshold = threshold;
}
private static void insertionSort(int[] array, int left, int right) {
for (int i = left + 1; i <= right; i++) {
final int key = array[i];
int j = i - 1;
while (j >= left && array[j] > key) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = key;
}
}
@Override
protected void compute() {
if (max > min) {
if (max - min < threshold) {
insertionSort(array, min, max);
} else {
final int pivotIndex = QuicksortRecursive.partition(array, min, max);
invokeAll(new QuicksortTask(array, min, pivotIndex - 1, threshold), new QuicksortTask(array, pivotIndex + 1, max, threshold));
}
}
}
}