-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathMerge.h
52 lines (41 loc) · 1.17 KB
/
Merge.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
#ifndef ALGS4_MERGE_H
#define ALGS4_MERGE_H
#include "Sorting.h"
class Merge : public Sorting {
private:
template<typename T>
static void sort(std::vector<T> &a, int lo, int hi);
protected:
template<typename T>
inline static std::vector<T> aux;
template<typename T>
static void merge(std::vector<T> &a, int lo, int mid, int hi);
public:
template<typename T>
static void sort(std::vector<T> &a);
};
template<typename T>
void Merge::sort(std::vector<T> &a, int lo, int hi) {
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, lo, mid);
sort(a, mid + 1, hi);
merge(a, lo, mid, hi);
}
template<typename T>
void Merge::merge(std::vector<T> &a, int lo, int mid, int hi) {
int i = lo, j = mid + 1;
for (int k = lo; k <= hi; ++k) aux<T>[k] = a[k];
for (int k = lo; k <= hi; ++k) {
if (i > mid) a[k] = aux<T>[j++];
else if (j > hi) a[k] = aux<T>[i++];
else if (less(aux<T>[j], aux<T>[i])) a[k] = aux<T>[j++];
else a[k] = aux<T>[i++];
}
}
template<typename T>
void Merge::sort(std::vector<T> &a) {
aux<T> = std::vector<T>(a.size());
sort(a, 0, a.size() - 1);
}
#endif //ALGS4_MERGE_H