1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package ch.hslu.exercises.sw11.ex2.quicksort;
17
18 import java.util.concurrent.RecursiveAction;
19
20
21
22
23 public final class QuicksortTask extends RecursiveAction {
24
25 private final int threshold;
26 private final int[] array;
27 private final int min;
28 private final int max;
29
30
31
32
33
34
35 public QuicksortTask(int[] array, final int threshold) {
36 this(array, 0, array.length - 1, threshold);
37 }
38
39 private QuicksortTask(final int[] array, final int min, final int max, final int threshold) {
40 this.array = array;
41 this.min = min;
42 this.max = max;
43 this.threshold = threshold;
44 }
45
46 private static void insertionSort(int[] array, int left, int right) {
47 for (int i = left + 1; i <= right; i++) {
48 final int key = array[i];
49 int j = i - 1;
50 while (j >= left && array[j] > key) {
51 array[j + 1] = array[j];
52 j--;
53 }
54 array[j + 1] = key;
55 }
56 }
57
58 @Override
59 protected void compute() {
60 if (max > min) {
61 if (max - min < threshold) {
62 insertionSort(array, min, max);
63 } else {
64 final int pivotIndex = QuicksortRecursive.partition(array, min, max);
65 invokeAll(new QuicksortTask(array, min, pivotIndex - 1, threshold), new QuicksortTask(array, pivotIndex + 1, max, threshold));
66 }
67 }
68 }
69
70 }