-
Notifications
You must be signed in to change notification settings - Fork 52
/
MergeSort
53 lines (52 loc) · 936 Bytes
/
MergeSort
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
#include<bits/stdc++.h>
using namespace std;
void merge(int a[],int lo,int mid,int hi){
int i = lo;
int j = mid+1;
vector<int> v;
while(i<=mid && j<=hi){
if(a[i]<a[j])
{
v.push_back(a[i]);
// cout<<a[i]<<" ";
i++;
}
else{
v.push_back(a[j]);
j++;
}
}
while(i<=mid)
{
v.push_back(a[i]);
i++;
}
while(j<=hi){
v.push_back(a[j]);
j++;
}
int l = lo;
for(int k=0;k<v.size();k++){
a[l] = v[k];
l++;
}
}
void merger(int a[],int lo,int hi){
if(lo>=hi)
return;
int mid = lo+(hi-lo)/2;
merger(a,lo,mid);
merger(a,mid+1,hi);
merge(a,lo,mid,hi);
}
int main(){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
merger(a,0,n-1);
for(int i=0;i<n;i++){
cout<<a[i]<<" ";
}
}