-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmergesort.cpp
More file actions
43 lines (36 loc) · 782 Bytes
/
mergesort.cpp
File metadata and controls
43 lines (36 loc) · 782 Bytes
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
#include <bits/stdc++.h>
using namespace std;
void merge(vector<int>& a, int l, int r, int m){
int i = l, j = m + 1, k = 0;
vector<int> c;
while(i<=m && j<=r){
if(a[i] < a[j]){
c.push_back(a[i++]);
}else{
c.push_back(a[j++]);
}
}
while(i<=m){
c.push_back(a[i++]);
}
while(j<=r){
c.push_back(a[j++]);
}
for(int i = l;i<=r; ++i){
a[i] = c[k++];
}
}
void mergesort(vector<int>&a, int l, int r){
if(l<r){
int m = (r + l) / 2;
mergesort(a, l, m);
mergesort(a, m + 1, r);
merge(a, l, r, m);
}
}
int main(){
vector<int> a = {5, 3, 2, 7, 8, 9, 1};
mergesort(a, 0, a.size() - 1);
for(int i : a)
cout<<i<<" ";
}