归并排序
归并的意思是: 先递归拆分排序,再合并每个小的(相临的)数组。
下面是代码(C++14)
#include <iostream>
#include <vector>
#include <deque>
#include <iterator>
#include <algorithm>
using std::cout;
using std::endl;
using std::copy;
using std::vector;
using std::deque;
using std::ostream_iterator;
template <typename OS, typename C>
OS & Print(OS & os, const C & c)
{
using T = typename C::value_type;
copy(begin(c), end(c), ostream_iterator<T>(os, "\t"));
return os;
}
template <typename C, typename ST = typename C::size_type>
void Merge(C & c, ST first, ST middle, ST last)
{
ST f = first,
m = middle + 1,
k = 0;
C temp (last - first);
// 合并的时候排序
while (f <= middle && m <= last)
{
if (c[f] < c[m])
{
temp[k++] = c[f++];
}
else
{
temp[k++] = c[m++];
}
}
// 两段区间, 谁还没复制完, 继续
while (f <= middle)
{
temp[k++] = c[f++];
}
while (m <= last)
{
temp[k++] = c[m++];
}
// 把 temp 复制回 c, 覆盖 c 中的[first, last] 区域
// (因为 temp 就是 c 中这个区域 已经排序的值)
copy_n(temp.begin(), k, c.begin() + first);
}
// 排序实际上是最简单的, 也就是个递归操作: 分别对前后两部分进行排序, 然后再合并
template <typename C, typename ST = typename C::size_type>
void Sort(C & c, ST first, ST last)
{
if (first < last)
{
ST mid = (first + last) / 2;
Sort(c, first, mid);
Sort(c, mid + 1, last);
Merge(c, first, mid, last);
}
}
int main()
{
vector<int> vi {10, 9, 8, 15, 7, 24, 5, 4, 2, 95};
Print(cout, vi) << endl;
Sort(vi, (vector<int>::size_type)0, vi.size() - 1);
Print(cout, vi) << endl << "--------------" << endl;
deque<double> di {1.0, 9.4, 3.88, 1.5, 7.8, 2.4, 5.9, 4.2, 2.8, 9.5};
Print(cout, di) << endl;
Sort(di, (deque<int>::size_type)0, vi.size() - 1);
Print(cout, di) << endl << "--------------" << endl;
}