码迷,mamicode.com
首页 > 其他好文 > 详细

MergeSort-vector

时间:2019-10-23 22:30:06      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:for   int   oid   cout   merge   ++   str   ==   mergesort   

归并排序-vector实现

#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;

void Merge(vector<int> &v, int L, int M, int R)
{
    //拆分成两个vector:left和right
    //vector(begin,end):复制[begin,end)区间内另一个数组的元素到vector中
    vector<int> left(v.begin() + L, v.begin() + M + 1);
    vector<int> right(v.begin() + M + 1, v.begin() + R + 1);
    //两个迭代器
    auto left_it = left.cbegin();
    auto right_it = right.cbegin();
    int i = L;
    //合并vector
    while (left_it != left.cend() && right_it != right.cend())
    {
        if (*left_it < *right_it)
            v[i++] = *(left_it++);
        else
            v[i++] = *(right_it++);
    }
    while (left_it != left.cend())
        v[i++] = *(left_it++);
    while (right_it != right.cend())
        v[i++] = *(right_it++);
}
//Ascending
void MergeSort(vector<int> &v, int L, int R)
{
    if (L == R)
        return;
    else
    {
        MergeSort(v, L, (L + R) / 2);
        MergeSort(v, (L + R) / 2 + 1, R);
        Merge(v, L, (L + R) / 2, R);
    }
}
int main(void)
{
    vector<int> v = {4, 3, 2, 1, 0};
    MergeSort(v, 0, 4);
    for (int i = 0; i < 5; i++)
        cout << v[i] << endl;
    return 0;
}

MergeSort-vector

标签:for   int   oid   cout   merge   ++   str   ==   mergesort   

原文地址:https://www.cnblogs.com/vlyf/p/11729017.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!