-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_sort.cpp
71 lines (56 loc) · 1.17 KB
/
merge_sort.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
#include <iostream>
#include <vector>
#include <climits>
#include <cassert>
#include "merge_sort.hpp"
#include "my_tools.hpp"
using namespace std;
static void merge(vector<int> &a, int begin, int mid, int end)
{
vector<int> b(mid - begin + 1);
vector<int> c(end - mid + 1);
int i, j;
for (i = 0; i < mid - begin; i++) {
b[i] = a[i + begin];
}
b[i] = INT_MAX;
for (i = 0; i < end - mid; i++) {
c[i] = a[i + mid];
}
c[i] = INT_MAX;
i = j = 0;
for (int k = begin; k < end; k++) {
if (b[i] < c[j]) {
a[k] = b[i++];
} else {
a[k] = c[j++];
}
}
}
static void merge_sort_recursive(vector<int> &a, int begin, int end)
{
if (begin >= end - 1) return;
int mid = (begin + end)/2;
merge_sort_recursive(a, begin, mid);
merge_sort_recursive(a, mid, end);
merge(a, begin, mid, end);
}
void merge_sort(vector<int> &a)
{
ScopedClock cl(__FUNCTION__);
return merge_sort_recursive(a, 0, a.size());
}
void test_merge_sort()
{
for (int i = 0; i < 1000; i++) {
int n = rand_int(1, 1000000);
vector<int> a(n);
for (int j = 0; j < n; j++) {
a[j] = rand_int(1, 1000000);
}
merge_sort(a);
for (int j = 1; j < n; j++) {
assert(a[j] >= a[j-1]);
}
}
}