forked from kingroryg/DSA
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMergeSort.cpp
More file actions
62 lines (53 loc) · 667 Bytes
/
Copy pathMergeSort.cpp
File metadata and controls
62 lines (53 loc) · 667 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
using namespace std;
void merge(int a[],int l,int m,int r)
{
int i = l,j=m+1,k=l;
int *c = new int[50];
while((i<=m) && (j<=r))
{
if(a[i]<a[j])
{
c[k++] = a[i++];
}
else
{
c[k++] = a[j++];
}
}
while(i<=m)
{
c[k++] = a[i++];
}
while(j<=r)
{
c[k++] = a [j++];
}
for(i=l;i<=r;i++)
{
a[i] = c[i];
}
}
void mergesort(int a[],int l,int r)
{
int mid;
if(l<r)
{
mid = (l+r)/2;
mergesort(a,l,mid);
mergesort(a,mid+1,r);
merge(a,l,mid,r);
}
}
int main()
{
int *a,n,i;
cin>>n;
a = new int[n];
for(i=0;i<n;i++)
cin>>a[i];
mergesort(a,0,n-1);
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}