-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort.cpp
57 lines (50 loc) · 915 Bytes
/
MergeSort.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
#include <iostream>
using namespace std;
int a[100],b[100];
void mergearr(int l,int mid, int r)
{
int i=l,j=mid+1,k=0;
while(i<=mid && j<=r)
{
if(a[i]<a[j])
b[k++]=a[i++];
else
b[k++]=a[j++];
}
while(j<=r)
b[k++]=a[j++];
while(i<=mid)
b[k++]=a[i++];
for(int p=l;p<=r;p++)
a[p]=b[p-l];
}
void mergesort(int l,int r)
{
if(l+1==r)
{
if(a[l]>a[r])
{
int temp=a[r];
a[r]=a[l];
a[l]=temp;
}
return;
}
if(l==r)
return;
int mid=(l+r)/2;
mergesort(l,mid);
mergesort(mid+1,r);
mergearr(l,mid,r);
}
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
cin>>a[i];
mergesort(0,n-1);
for(int i=0;i<n;i++)
cout<<a[i];
return 0;
}