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. 为什么要有binary-to-text encoding?

    在wikipedia上看MIME的介绍的时候,有一节是关于Content-Transfer-Encoding的,里面提到了binary-to-text encoding,我就想,既然计算机中的信息使用 ...

  2. cocos2d-x学习笔记------动画人物跑起来吧!

    学习总结: 1.sprintf用来格式化字符串 2.CCSpriteFrame:: frameWithTexture通过图片名创建的时候需要的参数Texture2D创建使用CCTextureCache ...

  3. python27读书笔记0.1

    --Notes: 测试环境:Windows ,python 2.7.3,python 自带的IDLE #-*- coding: utf-8 -*- # First Lesson# --- Line s ...

  4. 防止横竖屏时,iphone自动缩放的一段js代码

    function orientation_change() {     var viewport = document.querySelector('meta[name="viewport& ...

  5. codeforces 388C Fox and Card Game

    刚刚看到这个题感觉是博弈题: 不过有感觉不像,应该是个贪心: 于是就想贪心策略: 举了一个例子: 3 3 1 2 3 4 3 4 1 2 5 4 1 2 5 8 如果他们两个每次都拿对自己最有利的那个 ...

  6. 介绍一个超好用的HICHARTS扩展插件

    因为需要,所以HIGHCHARTS了解一下是很有必要的. 但原始应用确实效率不行. 刚好,现在有个需求是从一系列的JSON里抽出表格数据,再显示图形. jquery.highchartsTable.j ...

  7. 李洪强iOS开发本人集成环信的经验总结_02_基本配置

     李洪强iOS开发本人集成环信的经验总结_02_基本配置 来到APPdelegate中做一些配置 01 - 导入头文件 02 - 在didFinishLaunchingWithOptions用法总结 ...

  8. CC_UNUSED_PARAM 宏含义的解释

    #define CC_UNUSED_PARAM(unusedparam) (void)unusedparam 这个宏完全没有执行任何命令,这样写的原因主要是历史遗留原因,ojb-c不存在纯虚函数并且传 ...

  9. 使用GDI+ DrawDriverString实现行距及字符间距控制

    主要是要将一个标题和几段文字绘制到固定大小的图片上,如果一张放不下就生成多张.在使用DrawString是发现无法控制行距 namespace TibetTest {     public class ...

  10. 【HDOJ】1073 Online Judge

    这道题TLE了N多次,完全不明白为什么,稍微改了一下,居然过了.使用gets过的,看讨论帖有人还推荐用hash. #include <stdio.h> #include <strin ...