算法之奇偶交换排序

奇偶排序解开了冒泡排序每次迭代交换数据的相关性。它将排序分为两个过程,奇交换和偶交换。

  • 对于奇交换来说,它总是比较奇数索引及其相邻的后续元素。

  • 对于偶交换来说,它总是比较偶数索引及其相邻的后续元素。

  • 奇交换和偶交换会成对出现,这样能保证比较和交换涉及数组中的每一个元素。

奇偶交换的串行实现

public static void oddEventSort(int[] arr){
    int exchFlag = 1, start = 0;
    while(exchFlag == 1 || start == 1){
        exchFlag = 0;
        for(int i = start; i<arr.length-1; i+=2){
            if(arr[i] > arr[i+1]){ 
                int temp = arr[i];
                arr[i] = arr[i+1];
                arr[i+1] = temp;
                exchFlag = 1;   
            }
        }
        if(0 == start){
            start = 1;
        }else{
          start = 0;  
        }
    }
}

奇偶交换的并行实现

static int[] arr = {1, 4, 5, 2, 3};
static ExecutorService pool = Executors.newCachedThreadPool();
static int exchFlag = 1;
static synchronized void setExchFlag(int v){
    exchFlag = v;
}
static synchronized int getExchFlag(){
    return exchFlag;
}
public static class oddEventSortTask implements Runnable {
    int i ;
    CountDownLatch latch;
    public oddEventSortTask(int i, CountDownLatch latch){
        this.i = i;
        this.latch =  latch;
    }
    @Override
    public void run(){
        if(arr[i] > arr[i+1]){
            int temp = arr[i];
            arr[i] = arr[i+1];
            arr[i+1] = temp;
            exchFlag = 1;
        }
        latch.countDown();
    }
}

public static void pOddEventSort(int[] arr) throws InterruptedException{
    int start = 0;
    while(1 == getExchFlag() || 1 == start){
        setExchFlag(0);
        //偶数的数组长度,当start为1时,只有len/2-1个线程
        CountDownLatch latch = new CountDownLatch(arr.length/2 - (arr.length%2 == 0?start : 0));
        for(int i =start; i<arr.length-1; i +=2){
            pool.submit(new oddEventSortTask(i, latch));
        }
        //等待所有线程结束
        latch.await();
        if(0 == start){
            start = 1;
        }else{
            start = 0;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李景琰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值