MergeSort-vector
Posted vlyf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MergeSort-vector相关的知识,希望对你有一定的参考价值。
归并排序-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的主要内容,如果未能解决你的问题,请参考以下文章