希尔排序的并行排序

希尔排序

在学习《实战高并发程序设计》第二版这本书的时候,在学习希尔排序的并发解法时,感觉书里的解法好像有点问题(也可能是自己的问题),于是把他记录一下。
具体位位置是书中253页37行代码处。
书里,每个循环时线程的开启数是arr.length-h,我感觉开启 h个线程就可以了,也就是间隔是多少,便开几个线程。代码如下:

代码

package com.bh.demo;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ClassName:ParallShellSort
 * Package:com.bh.demo
 * Description:
 *
 * @Date:2019/7/31 17:44
 * @Auther:zy1704528@buaa.edu.cn
 */
public class ParallShellSort {

    static int[] arr = {9,8,7,6,5,4,3,2,1,0,12,11,10,45,87,80,34,33,32,21};
    static ExecutorService pool = Executors.newCachedThreadPool();

    public static class ShelSort implements Runnable{

        CountDownLatch cdLatch;
        int d;
        int start;

        public ShelSort(CountDownLatch cdLatch, int d, int start) {
            this.cdLatch = cdLatch;
            this.d = d;
            this.start = start;
        }

        @Override
        public void run() {
            //单个线程的任务--排序
            int temp;
            for(int i = start;i < arr.length;i += d){
                int j = i - d;
                temp = arr[i];
                while(j >= 0 && temp < arr[j]){
                    arr[j + d] = arr[j];
                    j -= d;
                }
                arr[j + d] = temp;
            }
            cdLatch.countDown();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int d = arr.length;
        while (d > 0) {
            d /= 2;
            //和书里的主要不同之处
            CountDownLatch countDownLatch = new CountDownLatch(d);
            for(int i = 0;i < d;i++){
                pool.submit(new ShelSort(countDownLatch,d,i));
            }
            countDownLatch.await();
        }
        for(int num : arr){
            System.out.print(num + " ");

        }
    }

}

**

结果:

**


0 1 2 3 4 5 6 7 8 9 10 11 12 21 32 33 34 45 80 87 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值