1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
template <typename srcIterator, typename tempIterator>
void merge(
srcIterator left,
srcIterator middle,
srcIterator right,
tempIterator temp)
{
auto t = temp;
auto i = left;
auto j = middle;
while (i != middle && j != right) *t++ = *i <= *j ? *i++ : *j++;
while (i != middle) *t++ = *i++;
while (j != right ) *t++ = *j++;
std::copy(temp, t, left);
}
template <typename srcIterator, typename tempIterator>
void merge_sort(
srcIterator left,
srcIterator right,
tempIterator temp)
{
auto dist = std::distance(left, right);
if (dist > 1) {
auto m = std::next(left, dist / 2);
merge_sort(left, m, temp);
merge_sort(m, right, temp);
merge(left, m, right, temp);
}
}
int main()
{
std::vector<int> v { 5, 3, 9, 1, 8, 0, 2, 6, 4, 7 };
std::vector<int> t(v.size());
merge_sort(v.begin(), v.end(), t.begin());
for (int n: v) std::cout << n << ' ';
std::cout << '\n';
}
|