-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathmerge_sort.cpp
66 lines (51 loc) · 905 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
#include<iostream>
using namespace std;
void merge(int *a,int low,int high)
{
int mid = (low+high)/2;
vector<int> left,right;
for(int i=low,i<=mid;i++)
left.push_back(a[i]);
for(int i=mid+1,i<=high;i++)
right.push_back(a[i]);
int i=0; int j=0;
for(int k=low;k<=high;k++){
if(i == left.size()){
a[k] = left[i++];
continue;
}
else if(j == right.size()){
a[k] = right[j++];
continue;
}
if(left[i] < right[j])
a[k] = left[i++];
else
a[k] = right[j++];
}
}
void merge_sort(int a[],int low,int high)
{
if(low<high)
{
int mid = (low+high)/2;
merge_sort(a,low,mid);
merge_sort(a,mid+1,high);
merge(a,low,high);
}
}
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int low = 0,high = n-1;
merge_sort(a,low,high);
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}