归并排序

//合并
void merge(int arr[],size_t s,size_t m,size_t e){

    size_t lsize = m-s;
    int left[lsize];
    size_t rsize = e-m;
    int right[rsize];
    for(size_t i=0,j=s;i!=lsize;++i){
        left[i] = arr[j++];
    }

    for(size_t i=0,j=m;i!=rsize;++i){
        right[i] = arr[j++];

    }

    size_t li = 0,ri = 0,index=s;
    while(li!=lsize&&ri!=rsize){
        if(left[li]<=right[ri]){
            arr[index++] = left[li++];
        }
        else{
            arr[index++] = right[ri++];
        }
    }

    while(li!=lsize){
        arr[index++] = left[li++];
    }
    while(ri!=rsize){
        arr[index++] = right[ri++];
    }

}

//递归
void merge_sort(int arr[],size_t s,size_t e){
    if(s+1<e){
        size_t m = (e+s)/2;
        merge_sort(arr,s,m);
        merge_sort(arr,m,e);
        merge(arr,s,m,e);
    }
}
 

你可能感兴趣的:(归并排序)