zoukankan      html  css  js  c++  java
  • 2-路归并排序的非递归写法

    《算法笔记》中摘取
    2-路归并排序的非递归写法主要考虑到这一点:每次分组时组内元素个数上线都是2的幂次。于是就可以想到这样的思路:令步长step的初值为2,然后减数组中每个step个元素作为一组,将其内部进行排序(即把左step / 2个元素与右step / 2个元素合并,而若元素个数不超过step / 2,则不操作);再令step 乘以 2,重复上面的操作,直到step / 2超过元素个数n。

    const int maxn = 100;
    //将数组A的[L1, R1]与[L2, R2]区间合并为有序区间(此处L2记为R1 + 1)
    void merge(int A[], int L1, int R1, int L2, int R2) {
        int i = L1, j = L2; //i指向A[L1], j指向A[L2]
        int temp[maxn], index = 0;  //temp临时存放合并后的数组,index为其下标
        while(i <= R1 && j <= R2) {
            if(A[i] <= A[j]) {  //如果A[i] <= A[j]
                temp[index++] = A[i++];     //将A[i]加入序列temp
            } else {            //如果A[i] > A[j]
                temp[index++] = A[j++];//将A[j]加入序列temp
            }
        }
        while(i <= R1) temp[index++] = A[i++]; //将[L1, R1]的剩余元素加入序列temp
        while(j <= R2) temp[index++] = A[j++]; //将[L2, R2]的剩余元素加入序列temp
        for(i = 0; i < index; i++) {
            A[L1 + i] = temp[i]; //将合并后的序列赋值回数组
        }
    }
    void mergeSort(int A[]) {
        //step为组内元素个数, step / 2为左子区间元素个数,注意等号可以不取
        //n为元素的个数
        for(int step = 2; step / 2 <= n; step *= 2) {
            //每step个元素一组,组内前step / 2和后step / 2个元素进行合并
            for(int i = 1; i <= n; i += step) { //对每一组
                int mid = i + step / 2 - 1; //左子区间元素个数为step / 2
                if(mid + 1 <= n) {  //右子区间存在元素则合并
                    //左子区间为[i, mid],右子区间为[mid+1, min(i+step-1, n)]
                    merge(A, i, mid, mid + 1, min(i + step - 1, n));
                }
            }
        }
    }
    
    //使用sort函数代替merge函数
    void mergeSort(int A[]) {
        //step为组内元素个数,step / 2为左子区间个数,注意等号可以不取
        for(int step = 2; step / 2 <= n; step *= 2) {
            //每step个元素一组,组内[i, min(i+step, n+ 1)]进行排序
            for(int i = 1; i <= n; i += step) {
                sotr(A + i, A + min(i + step, n + 1));
            }
            //此处可以输出归并排序的某一趟结束的序列
        }
    }
    
  • 相关阅读:
    ecshop与jquery冲突的解决方案
    ecshop_dwt_lbi模板添加
    ecshop模板基础知识
    bcc-tools工具之pidpersec
    bcc-tools工具之runqlen
    bcc-tools工具之runqlat
    bcc-tools工具之funccount
    cgroup介绍之为什么需要了解cgroup
    bcc-tools工具之funcslower
    git patch制作相关简介
  • 原文地址:https://www.cnblogs.com/isChenJY/p/11456802.html
Copyright © 2011-2022 走看看