-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mergesort.h
58 lines (43 loc) · 1.05 KB
/
Mergesort.h
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#ifndef MERGESORT_H
#define Thanksgiving_Mergesort_h
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
class MergeSort
{
public:
template<class T>
static vector<T> sort(vector<T> a) {
if ( a.size() == 1)
{ return a; }
typename vector<T>::iterator mid = a.begin() + a.size() / 2;
vector<T> left(a.begin(), mid);
vector<T> right(mid, a.end());
left = sort( left );
right = sort( right );
return merge( left, right);
}
template<class T>
static vector<T> merge(vector<T> &left, vector<T> &right) {
vector<T> result;
int l = 0, r = 0;
while ( l < left.size() && r < right.size()) {
if ( left[l] > right[r] ) {
result.push_back(right[r++]);
}
else {
result.push_back(left[l++]);
}
}
while ( l < left.size() ) {
result.push_back(left[l++]);
}
while ( r < right.size() ) {
result.push_back(right[r++]);
}
return result;
}
};
#endif