-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdemo_merge_sort_1.cpp
61 lines (48 loc) · 1.12 KB
/
demo_merge_sort_1.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
#include <iostream>
using namespace std;
#define MAX 500000
#define SENTINEL 2000000000
int L[MAX / 2 + 2], R[MAX / 2 + 2];
int cnt;
void merge(int A[], int n, int left, int mid, int right) {
int n1 = mid - left;
int n2 = right - mid;
for (int i = 0; i < n1; i++) L[i] = A[left + i];
for (int i = 0; i < n2; i++) R[i] = A[mid + i];
L[n1] = R[n2] = SENTINEL;
int i = 0, j = 0;
for (int k = left; k < right; k++) {
cnt++;
if (L[i] <= R[j]) {
A[k] = L[i++];
} else {
A[k] = R[j++];
}
}
}
void mergeSort(int A[], int n, int left, int right) {
if (left + 1 < right) {
int mid = (left + right) / 2;
mergeSort(A, n, left, mid);
mergeSort(A, n, mid, right);
merge(A, n, left, mid, right);
}
}
/**
* 10
* 8 5 9 2 6 3 7 1 10 4
*/
int main() {
int A[MAX], n, i;
cnt = 0;
cin >> n;
for (i = 0; i < n; i++) cin >> A[i];
mergeSort(A, n, 0, n);
for (i = 0; i < n; i++) {
if (i) cout << " ";
cout << A[i];
}
cout << endl;
cout << cnt << endl;
return 0;
}