【发布时间】:2016-08-25 10:10:31
【问题描述】:
我有这个类扩展RecursiveAction。
同一个类包含将数组作为参数和compute() 方法的构造函数。
在计算方法内部,它接下来说:
如果 array 长度大于 500,则将该数组分成两半并按 MergeSort.merge() 方法对其进行排序。如果数组长度小于 500,只需对 array 进行排序。
private static class SortTask extends RecursiveAction {
private final int THRESHOLD = 500;
private int[] list;
SortTask(int[] list) {
this.list = list;
}
@Override
protected void compute() {
if (list.length < THRESHOLD)
java.util.Arrays.sort(list);
else {
// Obtain the first half
int[] firstHalf = new int[list.length / 2];
System.arraycopy(list, 0, firstHalf, 0, list.length / 2);
// Obtain the second half
int secondHalfLength = list.length - list.length / 2;
int[] secondHalf = new int[secondHalfLength];
System.arraycopy(list, list.length / 2,
secondHalf, 0, secondHalfLength);
// Recursively sort the two halves
invokeAll(new SortTask(firstHalf),
new SortTask(secondHalf));
// Merge firstHalf with secondHalf into list
MergeSort.merge(firstHalf, secondHalf, list);
}
}
}
}
它说 “递归地对两半进行排序”,它通过以下方式做到这一点:
invokeAll(new SortTask(firstHalf), new SortTask(secondHalf));
这是否意味着每次创建new SortTask 对象时,都会调用compute() 方法?
【问题讨论】:
-
如果列表低于 THRESHOLD,则不会创建额外的 SortTask。否则,至少会创建一个额外的 SortTask 对(2、4、6、8...)。
标签: java data-structures mergesort