-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMergeSort.cpp
More file actions
73 lines (72 loc) · 1.35 KB
/
Copy pathMergeSort.cpp
File metadata and controls
73 lines (72 loc) · 1.35 KB
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
67
68
69
70
71
72
73
#include <bits/stdc++.h>
#define N 1000000007
#define M 1000000
using namespace std;
typedef long long int lli;
void mergea(int *a,int l,int mid,int h)
{
//cout<<"Merging"<<endl;
int l1=mid-l+1;
int l2=h-mid;
int L[l1],H[l2];
for(int i=0;i<l1;i++)
L[i]=a[l+i];
for(int i=0;i<l2;i++)
H[i]=a[mid+1+i];
int ptr1=0,ptr2=0,i=l;
while(ptr1<l1&&ptr2<l2)
{
if(L[ptr1]<=H[ptr2])
{
a[i]=L[ptr1];
ptr1++;
}
else
{
a[i]=H[ptr2];
ptr2++;
}
i++;
}
while(ptr1<l1)
{
a[i]=L[ptr1];
ptr1++;
i++;
}
while(ptr2<l2)
{
a[i]=H[ptr2];
ptr2++;
i++;
}
}
void mergesort(int *a,int l,int h)
{
//cout<<l<<" "<<h<<endl;
if(l<h)
{
int mid=(l+h)/2;
mergesort(a,l,mid);
mergesort(a,mid+1,h);
mergea(a,l,mid,h);
}
}
int main()
{
int n;
cout<<"Enter number of elements"<<endl;
cin>>n;
int *a=(int *)malloc(n*sizeof(int));
cout<<"Enter elements"<<endl;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
//cout<<"elements"<<endl;
mergesort(a,0,n-1);
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}