package com.rationalcoding.sort;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future; /**
*
* @author Phani
*
* This is implementation of a multi threaded merge sort. First input
* array is divided into small chunks. Each chunk is sorted individually
* using Arrays.sort method which implements insertion sort Then all the
* chunks are merged in bottom up manner by doubling the width after
* each step
*
*/
public class MultiThreadedMergeSort extends SequentialMergeSort { private final int DEFAULT_POOL_SIZE = 100;
private final int DEFAULT_CHUNK_SIZE = 1000;
private ExecutorService pool = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE);
private int[] arr; @SuppressWarnings("rawtypes")
@Override
public void sort(int[] arr) {
this.arr = arr; // handle null inputs
if (arr == null) {
throw new IllegalArgumentException("Input array cannot be null");
} if (arr.length == 0 || arr.length == 1) {
// already sorted return
return;
} // width is chunks we are diving the array into
int width = DEFAULT_CHUNK_SIZE;
if (width > 1) {
// apply insertion sort on chunks and then merge the chunks
ArrayList<Future> subTasks = new ArrayList<Future>();
for (int i = 0; i < arr.length; i = i + width) {
int start = i;
int end = i + width;
if (end > arr.length) {
end = arr.length;
}
// add the runnables to pool
subTasks.add(pool.submit(new InsertionSortRunnable(start, end)));
} // wait for the tasks to finish
// join all the threads to main thread
for (Future f : subTasks) {
try {
f.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
} // apply merging on already sorted chunks
for (; width < arr.length; width = width * 2) {
ArrayList<Future> tasks = new ArrayList<Future>();
for (int i = 0; i < arr.length; i = i + 2 * width) {
int rStart = i;
int rEnd = i + width - 1;
int lEnd = i + 2 * width - 1;
if (lEnd >= arr.length) {
lEnd = arr.length - 1;
}
tasks.add(pool.submit(new MergeSortRunnable(rStart, rEnd, lEnd)));
}
// wait for all threads to finish
for (Future f : tasks) {
try {
f.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} } } private class InsertionSortRunnable implements Runnable {
private int start;
private int end; public InsertionSortRunnable(int start, int end) {
this.start = start;
this.end = end;
} @Override
public void run() {
Arrays.sort(arr, start, end);
} } private class MergeSortRunnable implements Runnable { private int start;
private int end;
private int mid; public MergeSortRunnable(int start, int mid, int end) {
this.start = start;
this.end = end;
this.mid = mid;
} @Override
public void run() {
if (start < end && mid <= end) {
merge(arr, start, mid, end);
} } } }

多线程归并排序(摘自githhub)的更多相关文章

  1. 多线程归并排序的实现 java

    多线程是非常适合归并排序的,因为归并排序是分治法,所以分割后可以独立运行,最后将结果归并起来就行了.如何写一个多线程程序呢?今天无聊,总结一下啊. 首先写个普通的归并排序,以后的多线程就调用这个排序. ...

  2. 归并排序 求逆序数 链表的归并排序 多线程归并排序 java

    import java.util.Scanner; public class Main { private static int count=0; public static void mergeso ...

  3. .net多线程归并排序

    一.概述 在了解排序算法的同时,想到用多线程排序减少排序的时间,所以写了一个简单的示例,加深印象.下面是具体代码 二.内容 环境:vs2017,.net  core 2.2 控制台程序. 运行时使用r ...

  4. java并发多线程(摘自网络)

    1. 进程和线程之间有什么不同? 一个进程是一个独立(self contained)的运行环境,它可以被看作一个程序或者一个应用.而线程是在进程中执行的一个任务.Java运行环境是一个包含了不同的类和 ...

  5. pthread 多线程基础

    本文主要介绍如何通过 pthread 库进行多线程编程,并通过以下例子进行说明. 基于莱布尼兹级数计算 \(\pi\) . 多线程归并排序 参考文章: [1] https://computing.ll ...

  6. 秋招落幕,对自己的总结by2018-10-20

    在今天阿里沟通offer完毕,正式三方也确定了,一切如梦,想想1月的自己还担心未来的自己会花落谁家,到10月的今天,一切尘埃落地.一直不怎么喜欢总结自己的历程,今天无聊的我也总结一波吧. 准确的说没有 ...

  7. java归并排序,单线程vs多线程

    一.什么是归并排序 归并排序又称合并排序,它是成功应用分治技术的一个完美例子.对于一个需要排序的数组A[0..n-1],归并排序把它一分为二:A[0..n/2-1]和A[n/2..n-1],并对每个子 ...

  8. 多线程外排序解决大数据排序问题2(最小堆并行k路归并)

    转自:AIfred 事实证明外排序的效率主要依赖于磁盘,归并阶段采用K路归并可以显著减少IO量,最小堆并行k路归并,效率倍增. 二路归并的思路会导致非常多冗余的磁盘访问,两组两组合并确定的是当前的相对 ...

  9. 多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类)

    前言:刚学习了一段机器学习,最近需要重构一个java项目,又赶过来看java.大多是线程代码,没办法,那时候总觉得多线程是个很难的部分很少用到,所以一直没下决定去啃,那些年留下的坑,总是得自己跳进去填 ...

随机推荐

  1. JS验证邮箱格式是否正确的代码

    验证邮箱格式是否正确的方法有很多,接下来为大家介绍下使用js是如何做到的 复制代码代码如下: /*  *验证邮箱格式是否正确  *参数strEmail,需要验证的邮箱  */ www.jbxue.co ...

  2. Python3.4 多线程

    线程安全和全局解释器锁 Thread State and the Global Interpreter Lock 总结: 通过使用GIL后, Python多线程安全, 并且数据保持同步. Python ...

  3. Popen No such file or directory 错误

    File , in reload_config stderr=PIPE, env={"PATH": '', "HOME": "/root"} ...

  4. 成为Java GC专家(3)—如何优化Java垃圾回收机制

    为什么需要优化GC 或者说的更确切一些,对于基于Java的服务,是否有必要优化GC?应该说,对于所有的基于Java的服务,并不总是需要进行GC优化,但前提是所运行的基于Java的系统,包含了如下参数或 ...

  5. javascript debut trick, using the throw to make a interrupt(breakpoint) in your program

    console.log('initialize'); try { throw "breakPoint"; } catch(err) {} when I debug the extj ...

  6. C# 操作mongodb 分组

    c#操作mongodb的分组的简单例子: 1.首先要下载c#对应的mongodb驱动,官方下载地址:https://github.com/mongodb/mongo-csharp-driver/rel ...

  7. python @property 属性

    在绑定属性时,如果我们直接把属性暴露出去,显然不合适,是通过getter和setter方法来实现的,还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性: class P ...

  8. BZOJ 3901 棋盘游戏 解题报告

    这题有个重要性质: 我们设 Flag[i][j] 表示 (i, j) 是否被奇数个操作所覆盖, 也就是操作次数对 2 取模. 设 x = (n + 1) / 2. 那么对于所有的合法的操作方案, 令 ...

  9. Ubuntu下使用ap-hotspot出现“Another process is already running"问题的解决方案

    参考Problem with ap-hotspot 问题描述: This is the message displayed in my terminal screen when I typed sud ...

  10. 将cocos2dx项目从VS移植到Eclipse

    本文转自:http://www.cnblogs.com/Z-XML/p/3349518.html 引言:我们使用cocos2d-x引擎制作了一款飞行射击游戏,其中创新性地融入了手势识别功能.但是我们在 ...