-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge_sort.cpp
69 lines (53 loc) · 962 Bytes
/
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
#include<bits/stdc++.h>
using namespace std;
void merge(vector<int>& arr, int l, int mid, int r){
int l1 = mid - l + 1;
int l2 = r - mid;
vector<int> a1;
vector<int> a2;
for(int i = 0; i < l1; i++) {
a1.emplace_back(arr[l + i]);
}
for(int i = 0; i < l2; i++) {
a2.emplace_back(arr[mid + 1 + i]);
}
int i = 0, j = 0, k = l;
while(i < l1 && j < l2) {
if(a1[i] < a2[j]) {
arr[k++] = a1[i++];
}else {
arr[k++] = a2[j++];
}
}
while(i < l1) {
arr[k++] = a1[i++];
}
while(j < l2) {
arr[k++] = a2[j++];
}
}
void mergeSort(vector<int>& arr, int l, int r) {
if(l < r) {
int mid = (l + r) / 2;
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
}
int main() {
int n;
cin>>n;
int count = 0;
vector<int> arr;
for(int i = 0; i < n; i++) {
int x;
cin>>x;
arr.emplace_back(x);
}
mergeSort(arr, 0, n-1);
for(auto it: arr) {
cout<<it<<" ";
}
cout<<endl;
cout<<count<<endl;
}