-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mergesort.cpp
69 lines (61 loc) · 1.29 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
#include <iostream>
#include <stdio.h> // prinf,scanf
#include <stdlib.h> // atoi
#include <math.h>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <iomanip> // setprecision
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define debug(x) cout << #x << " = " << x << endl;
#define debret(x) debug(x) ; return 0
using namespace std;
void Merge(int A[],int left,int mid,int right);
void MergeSort(int A[],int left, int right);
int cnt = 0;
int main(void){
int n;
cin >> n;
int A[n];
REP(i,n) cin >> A[i];
MergeSort(A,0,n);
REP(i,n){
if(i) cout << " ";
cout << A[i];
}
cout << endl << cnt << endl;
return 0;
}
void Merge(int A[],int left,int mid,int right){
int n1 = mid - left;
int n2 = right - mid;
int L[n1];
int R[n2];
REP(i,n1) L[i] = A[left + i];
REP(i,n2) R[i] = A[mid + i];
const int INF = 1 << 29;
L[n1] = INF;
R[n2] = INF;
int i = 0, j = 0;
FOR(k,left,right){
if(L[i] <=R[j]){
A[k] = L[i];
++i;
++cnt;
}else{
A[k] = R[j];
++j;
++cnt;
}
}
}
void MergeSort(int A[],int left, int right){
if(left + 1 < right){
int mid = (left + right)/2;
MergeSort(A, left, mid);
MergeSort(A, mid, right);
Merge(A, left, mid, right);
}
}