-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMergeSort.cpp
More file actions
64 lines (57 loc) · 1.1 KB
/
MergeSort.cpp
File metadata and controls
64 lines (57 loc) · 1.1 KB
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
#include <iostream>
#include <vector>
using namespace std;
// merge data index [low, mid] and (mid, high]
void Merge(vector<int> & vec, int low, int mid, int high)
{
vector<int> lth(vec.begin() + low, vec.begin() + mid + 1), rth(vec.begin() + mid + 1, vec.begin() + high + 1);
int lindex = 0, rindex = 0, index = low;
while (lindex < lth.size() && rindex < rth.size())
{
if (lth[lindex] < rth[rindex])
{
vec[index++] = lth[lindex++];
}
else
{
vec[index++] = rth[rindex++];
}
}
while (lindex < lth.size())
{
vec[index++] = lth[lindex++];
}
while (rindex < rth.size())
{
vec[index++] = rth[rindex++];
}
}
// data index range [low, high]
void MergeSort(vector<int> & vec, int low, int high)
{
if (low < high)
{
int mid = low + (high - low) / 2;
MergeSort(vec, low, mid);
MergeSort(vec, mid + 1, high);
Merge(vec, low, mid, high);
}
}
int main()
{
vector<int> vec;
vec.reserve(32);
for (int i = 10; 0 < i; --i)
{
for (int j = 2; 0 < j; --j)
{
vec.push_back(i);
}
}
MergeSort(vec, 0, vec.size() - 1);
for (int item : vec)
{
cout << item << " ";
}
cout << endl;
}