归并排序

void MergeSort(__int64* a,int first,int last,__int64* temp){ //对数组a排序,中间结果存在temp中
    if (first < last){ //二分到元素只有一个 
        int mid = (first + last)/2;
        MergeSort(a,first,mid,temp);//对左半部分排序
        MergeSort(a,mid+1,last,temp);//对右半部分排序
        Merge(a,first,mid,last,temp);//合并
    }
}
void Merge(__int64* a,int first,int mid,int last,__int64* temp){
    int i = first,j = mid + 1,k = 0;
    int m = mid, n = last;
    while (i <= m && j <= n){//循环到其中一边为空为止
        if (a[i] <= a[j]) //左边的小于等于右边的
            temp[k++] = a[i++]; //把左边的元素加入到temp中
        else
            temp[k++] = a[j++]; //否则把右边的元素加入到temp中
    }
    while (i <= m)//如果左边还有剩,则把剩下的元素全加到temp中
        temp[k++] = a[i++];
    while (j <= n)//同上
        temp[k++] = a[j++];
    for (i = 0;i < k;i++)//temp复制到a中
        a[first+i] = temp[i];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值