ForkJoinPool实现快排

ForkJoin实现快速排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package me.learn.treads;

import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

public class FastSort<T extends Comparable<T>> extends RecursiveAction {
private final T[] arrays;
private int low;
private int high;

public FastSort(T[] arrays) {
this.arrays = arrays;
this.low = 0;
this.high = this.arrays.length-1;
}

public FastSort(T[] arrays, int low, int high) {
System.out.println(Arrays.toString(arrays));
this.arrays = arrays;
this.low = low;
this.high = high;
}

public static <T extends Comparable<T>> int partition(T[] arrays, int left, int right) {
int k = left;
T pivot = arrays[right];
for (int i=left; i<right; ++i)
if (arrays[i].compareTo(pivot) < 0) swap(arrays, i, k++);
swap(arrays, k, right);
return k;
}

static <T extends Comparable<T>> void swap(T[] arrays, int i, int j) {
if (i != j) {
T tmp = arrays[i];
arrays[i] = arrays[j];
arrays[j] = tmp;
}
}

@Override
protected void compute() {
if (low < high) {
int pivot = partition(arrays, low, high);
FastSort<T> fastSort1 = new FastSort<>(arrays, low, pivot-1);
FastSort<T> fastSort2 = new FastSort<>(arrays, pivot+1, high);
invokeAll(fastSort1, fastSort2);

}
}

public static void main(String[] argv) throws InterruptedException {
ForkJoinPool pool = ForkJoinPool.commonPool();
Integer[] arr = new Integer[]{3,7,8,5,2,1,9,5,4};
FastSort<Integer> fastSort = new FastSort<>(arr);
pool.submit(fastSort);
pool.shutdown();
pool.awaitTermination(1, TimeUnit.SECONDS);
System.out.println(Arrays.toString(arr));
}
}