class MergerSort extends RecursiveAction { private int[] array; private int begin, end, threshold; protected MergerSort(int[] array, int begin, int end, int threshold) { this.array = array; this.begin = begin; this.end = end; this.threshold = threshold; } private void merger(int begin, int mid, int end) { int i = begin, j = mid + 1, k = 0; int[] temp = new int[end - begin + 1]; while (i <= mid && j <= end) { if(array[i] < array[j]) temp[k++] = array[i++]; else temp[k++] = array[j++]; } while(i <= mid) temp[k++] = array[i++]; while(j <= end) temp[k++] = array[j++]; while(--k >= 0) array[end--] = temp[k]; } @Override protected void compute() { if (end - begin < threshold) { //小于阈值,使用一般排序算法 Arrays.sort(array, begin, end + 1); } else { //使用并发归并排序 int mid = (end - begin) / 2; MergerSort left = new MergerSort(array, begin, mid, threshold); MergerSort right = new MergerSort(array, mid + 1, end, threshold); left.fork(); right.fork(); left.join(); right.join(); merger(begin, mid, end); } } }
输出:
1 1 2 2 6 7 23 23 52 56 58 8 5 4 9 4 6 4 1 8 4 14 5 798 4 56 153 321 7 56 0 3 456 23 1 65 3 454 8 63 78
不知道你其他部分什么样子
不过一眼看去
int mid = (end - begin) / 2;
明显应该是int mid = (end + begin) / 2;