public static void mergeSort(int[] target){
sort(target,0,target.length);
}
private static void sort(int[] target,int start,int end){
if (end - start < 2){
return;
}
int index = (end + start) >> 1;
sort(target,start,index);
sort(target,index,end);
merge(target,start,end);
}
private static void merge(int[] target,int start,int end){
int index = (start + end) >> 1;
int[] arr = new int[end - start];
int length = 0;
for (int left = start,right = index;left < index && right < end ; length++){
if (target[left] < target[right]){
arr[length] = target[left];
left++;
}else {
arr[length] = target[right];
right++;
}
if (left == index){
int x = end - right;
System.arraycopy(target, right, arr, ++length, x);
length = length + x - 1;
}
if (right == end){
int x = index - left;
System.arraycopy(target, left, arr, ++length, x);
length = length + x - 1;
}
}
if (length > 0) System.arraycopy(arr, 0, target, start, length);
}
原本想使用fork/join 实现归并排序,测试发现其实并不合适,虽然都是采用分治思想但是在归并排序中,执行粒度太小,创建线程不如执行,并且合并还需要等待。
推荐:当排序量比较庞大时,可以采用多线程,为了线程资源浪费,可以分块归并,并且主线程也要执行分块中的一部分,然后主线程执行完一部分后在进行子线程join操作进行等待,最终进行合并操作。
多线程优化归并排序:分块合并与任务调度策略
本文探讨了为何在归并排序中使用Fork/Join不适合,提出通过分块归并策略,结合主线程参与和子线程协同,以减少线程创建和合并等待时间,提高大规模数据排序效率。
1583

被折叠的 条评论
为什么被折叠?



