数组归并排序代码实现(ForkJoin版):
/**
*
*/
package concurrent.forkjoin;
import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import algorithm.sort.MergeSortAlgorithm;
/**
* A merge sort demonstration algorithm with the fork-join framework(a parallelizable algorithm)
*
* 数组归并排序: http://blog.csdn.net/yang_net/archive/2010/08/01/5781012.aspx
*
* @author yangwm Aug 12, 2010 11:15:47 AM
*/
public class MergeSortForkJoin extends RecursiveAction {
/**
*
*/
private static final long serialVersionUID = -7490351302704617127L;
private static final int THRESHOLD = 4;
private final int[] number;
private int[] result;
public MergeSortForkJoin(int[] number) {
this.number = number;
}
@Override
protected void compute() {
if (number.length <= THRESHOLD) {
result = MergeSortAlgorithm.mergeSort(number);
} else {
int middle = number.length / 2;
/*
* Partition the list into two lists and sort them recursively
*/
int left[] = new int[middle];
for (int i = 0; i < middle; i++) {
left[i] = number[i];
}
int right[] = new int[number.length - middle];
for (int i = 0; i < number.length - middle; i++) {
right[i] = number[middle + i];
}
/*
* Merge the two sorted lists
*/
MergeSortForkJoin leftForkJoin = new MergeSortForkJoin(left);
MergeSortForkJoin rightForkJoin = new MergeSortForkJoin(right);
invokeAll(leftForkJoin, rightForkJoin); // coInvoke(leftForkJoin, rightForkJoin);
result = MergeSortAlgorithm.merge(leftForkJoin.result, rightForkJoin.result);
}
}
public int[] merge(int left[], int right[]) {
int[] result = new int[left.length + right.length];
int leftPos = 0;
int rightPos = 0;
int resultPos = 0;
while (leftPos < left.length && rightPos < right.length) {
/* Merge sorted sublists */
if (left[leftPos] <= right[rightPos]) {
result[resultPos++] = left[leftPos++];
} else {
result[resultPos++] = right[rightPos++];
}
}
if (leftPos < left.length) {
/* append left to result */
while (leftPos < left.length) {
result[resultPos++] = left[leftPos++];
}
} else {
/* append right to result */
while (rightPos < right.length) {
result[resultPos++] = right[rightPos++];
}
}
return result;
}
public static void main(String[] args) {
int[] number = { 4, 2, 1, 2, 7, 3, 9, 0, 0, 11, 10, 6, 15, 8 };
MergeSortForkJoin mergeSortForkJoin = new MergeSortForkJoin(number);
ForkJoinPool forkJoinPool = new ForkJoinPool();
forkJoinPool.invoke(mergeSortForkJoin);
System.out.println(Arrays.toString(mergeSortForkJoin.result));
}
}
输出:
[0, 0, 1, 2, 2, 3, 4, 6, 7, 8, 9, 10, 11, 15]
学习参考资料:
Stick a fork in it, Part I & Stick a fork in it, Part II : http://www.briangoetz.com/pubs.html
A Java ForkJoin Framework: http://gee.cs.oswego.edu/dl/papers/fj.pdf
JDK 7 中的 Fork/Join 模式 : http://www.ibm.com/developerworks/cn/java/j-lo-forkjoin/
RecursiveAction (Java Platform SE 7) : http://download.java.net/jdk7/docs/api/java/util/concurrent/RecursiveAction.html