-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergesort.h
59 lines (51 loc) · 1.3 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
59
#ifndef MERGESORT_H
#define MERGESORT_H
// merges subarray of the array
template <typename RandomIt>
void merge(RandomIt Infirst, RandomIt Inmid, RandomIt Inlast,
RandomIt Outfirst) {
auto iterleft = Infirst;
auto iterright = Inmid;
auto iterout = Outfirst;
while (iterleft != Inmid && iterright != Inlast) {
if (*iterleft <= *iterright) {
*iterout = *iterleft;
++iterleft;
} else {
*iterout = *iterright;
++iterright;
}
++iterout;
}
while (iterleft != Inmid) {
*iterout = *iterleft;
++iterleft;
++iterout;
}
while (iterright != Inlast) {
*iterout = *iterright;
++iterright;
++iterout;
}
while (Infirst != Inlast) {
*Infirst = *Outfirst;
++Infirst;
++Outfirst;
}
}
template <typename RandomIt>
void sort(RandomIt Infirst, RandomIt Inlast, RandomIt Outfirst) {
auto size = std::distance(Infirst, Inlast);
if (size > 1) {
auto mid = Infirst + size / 2 + size % 2;
int dist = std::distance(Infirst, mid);
sort(Infirst, mid, Outfirst);
sort(mid, Inlast, Outfirst + dist);
merge(Infirst, mid, Inlast, Outfirst);
}
}
template <typename Container>
void mergesort(Container& List, Container& Out) {
sort(List.begin(), List.end(), Out.begin());
}
#endif /* end of include guard: MERGESORT_H */