有一些排序算法如归并排序、快速排序等可以分解为子问题的算法是可以使用多线程来加速排序的,之前做了个小实验,测试了下自己写的MergeSort::parallelSort、QuickSort::parallelSort以及Arrays::sort、Arrays::parallelSort类库排序方法的速度,随机生成1千万个数据用于排序,使用-Xmx、-Xms设置了jvm内存尽可能大,因为每次排序都需要1千万个数据拷贝,所以使用-XX:+PrintGCDetails打印了GC细节以及GC带来的停顿,挺好玩的
1.算法代码和测试代码
MergeSort的代码如下:
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* Created by violetMoon on 2016/4/13.
*/
public class MergeSort {
public static <T extends Comparable<? super T>> void sort(T[] datas) {
sort(datas, 0, datas.length - 1);
}
public static <T extends Comparable<? super T>> void sort(T[] datas, int low, int high) {
Object[] bufs = new Object[datas.length];
sort(datas, low, high, bufs);
}
public static <T extends Comparable<? super T>> void parallelSort(T[] datas) {
parallelSort(datas, 0, datas.length - 1);
}
public static <T extends Comparable<? super T>> void parallelSort(T[] datas, int low, int high) {
ForkJoinPool pool = new ForkJoinPool();
Object[] bufs = new Object[datas.length];
MergeSortAction action = new MergeSortAction(datas, low, high, bufs);
pool.invoke(action);
pool.shutdown();
try {
pool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
static <T extends Comparable<? super T>> void sort(T[] datas, int low, int high, Object[] bufs) {
if (low >= high)
return;
int center = (low + high) / 2;
sort(datas, low, center);
sort(datas, center + 1, high);
merge(datas, low, center, high, bufs);
}
private static <T extends Comparable<? super T>> void merge(T[] datas, int leftPos, int center, int rightPos,
Object[] bufs) {
int cur = leftPos;
int leftCur = leftPos;
int rightCur = center + 1;
while (leftCur <= center && rightCur <= rightPos) {
if (datas[leftCur].compareTo(datas[rightCur]) < 0)
bufs[cur++] = datas[leftCur++];
else
bufs[cur++] = datas[rightCur++];
}
while (leftCur <= center)
bufs[cur++] = datas[leftCur++];
while (rightCur <= rightPos)
bufs[cur++] = datas[rightCur++];
for (int i = leftPos; i <= rightPos; ++i)
datas[i] = (T) bufs[i];
}
static class MergeSortAction<T extends Comparable<? super T>> extend