-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort.cpp
99 lines (82 loc) · 1.69 KB
/
MergeSort.cpp
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include "MergeSort.h"
#include <vector>
#include <ncurses.h>
#include <unistd.h>
void MergeSort::sort() {
mergeSort(0, vect.size() - 1);
}
void MergeSort::printSort() {
printGraph();
printMergeSort(0, vect.size() - 1);
}
void MergeSort::merge(const int start, const int mid, const int end) {
std::vector<int> temp;
int i, j;
i = start;
j = mid + 1;
while (i <= mid && j <= end) {
if (vect[i] <= vect[j]) {
temp.push_back(vect[i]);
i++;
} else {
temp.push_back(vect[j]);
j++;
}
}
while (i <= mid) {
temp.push_back(vect[i]);
i++;
}
while (j <= end) {
temp.push_back(vect[j]);
j++;
}
for (i = start; i <= end; ++i) {
vect[i] = temp[i - start];
}
}
void MergeSort::mergeSort(const int start, const int end) {
if (start < end) {
int m = (start + end) / 2;
mergeSort(start, m);
mergeSort(m + 1, end);
merge(start, m, end);
}
}
void MergeSort::printMerge(const int start, const int mid, const int end) {
std::vector<int> temp;
int i, j;
i = start;
j = mid + 1;
while (i <= mid && j <= end) {
if (vect[i] <= vect[j]) {
temp.push_back(vect[i]);
i++;
} else {
temp.push_back(vect[j]);
j++;
}
}
while (i <= mid) {
temp.push_back(vect[i]);
i++;
}
while (j <= end) {
temp.push_back(vect[j]);
j++;
}
for (i = start; i <= end; ++i) {
vect[i] = temp[i - start];
refresh();
usleep(10000);
clearPrintBar(i, vect[i]);
}
}
void MergeSort::printMergeSort(const int start, const int end) {
if (start < end) {
int m = (start + end) / 2;
printMergeSort(start, m);
printMergeSort(m + 1, end);
printMerge(start, m, end);
}
}