首页 > 代码库 > 经典白话算法之归并排序

经典白话算法之归并排序



void Merge(int A[],int p,int q,int r){
    int i,j,k;
    //计算子数组A[p..q]的元素个数
    int n1 = q - p + 1;
    //计算子数组A[q+1..r]元素个数
    int n2 = r - q;
    //创建子数组L,R
    int* L = (int*)malloc(sizeof(int)*(n1+1));
    int* R = (int*)malloc(sizeof(int)*(n2+1));
    //将子数组A[p..q]赋值到L数组
    for(i = 0;i < n1;i++){
        L[i] = A[p+i];
    }//for
    //将子数组A[q+1..r]赋值到R数组
    for(i = 0;i < n2;i++){
        R[i] = A[q+1+i];
    }//for
    //将哨兵置于数组末尾
    L[n1] = INT_MAX;
    R[n2] = INT_MAX;
    //合并
    i = 0;j = 0;
    for(k = p;k <= r;k++){
        if(L[i] <= R[j]){
            A[k] = L[i++];
        }else{
            A[k] = R[j++];
        }
    }//for
}
void MergeSort(int A[],int p,int r){
    //容错
    if(p >= r){
        return;
    }
    //分治
    int mid = (r + p) / 2;
    //递归调用
    MergeSort(A,p,mid);
    MergeSort(A,mid+1,r);
    //Cmbine
    Merge(A,p,mid,r);
}
调用:
int a[] = {1,3,5,7,8,2,3,5,6,9};
MergeSort(a,0,9);