首页 > 其他 > 详细

mergesort

时间:2019-10-26 09:01:15      阅读:76      评论:0      收藏:0      [点我收藏+]

Merge Sort

  • stable sort
  • most common implementation does not sort in place
  • external merge sort
void mergearray(vector<int> &a, int low, int mid, int high, vector<int> &tmp){
    // merge a[low,mid] and a[low+1,high]
    int i=low, j=mid+1;
    int k=0;
    while (i<=mid && j<=high){
        if (a[i]<a[j]) tmp[k++]=a[i++];
        else tmp[k++]=a[j++];
    }
    while (i<=mid) tmp[k++]=a[i++];
    while (j<=high) tmp[k++]=a[j++];
    // copy from tmp back to original array
    for (i=0;i<k;++i) a[low+i] = tmp[i];
}

void mergesort(vector<int> &a, int low, int high, vector<int> &tmp){
    if (low>=high) return;
    int mid=(low+high)/2;
    mergesort(a,low,mid,tmp);
    mergesort(a,mid+1,high,tmp);
    mergearray(a,low,mid,high,tmp);
}

int main() {
    vector<int> a={1,5,8,3,2};
    int n=a.size();
    vector<int> tmp(n);
    mergesort(a,0,n-1,tmp);
    for (auto x:a) cout<<x<< ;
    return 0;
}

Time Complexity: O(nlogn)

mergesort

原文:https://www.cnblogs.com/hankunyan/p/11741671.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!