-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergesort.cpp
More file actions
91 lines (80 loc) · 1.37 KB
/
mergesort.cpp
File metadata and controls
91 lines (80 loc) · 1.37 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include<iostream>
using namespace std;
class mrgsort
{
public:
int *A,n,p,r;
mrgsort()
{
cout<<"enter the no of element: ";
cin>>n;
p=0;r=n;
A=new int[n+1];
cout<<"enter the numbers"<<endl;
for(int i=1;i<=n;i++)
{
cout<<"A["<<i<<"]=";
cin>>A[i];
cout<<endl;
}
}
void msort(int p,int r);
void mergesort(int p,int q,int r);
void display()
{
cout<<"sorted numbers are:"<<endl;
for(int i=1;i<=n;i++)
{
cout<<"A["<<i<<"]=";
cout<<A[i];
}
}
};
void mrgsort::msort(int p,int r)
{
if(p<r)
{
int q=(p+r)/2;
msort(p,q);
msort(q+1,r);
mergesort(p,q,r);
}
return;
}
void mrgsort::mergesort(int p,int q,int r)
{
int i,j;
int n1=q-p+1;
int n2=r-q;
int *L,*R;
L=new int[n1+1];
R=new int[n2+1];
for(i=1;i<=n1;i++)
L[i]=A[p+i-1];
for(j=1;j<=n2;j++)
R[j]=A[q+j];
L[n1+1]=1111;
R[n2+1]=1111;
i=1;j=1;
for(int k=p;k<r;k++)
{
if(L[i]<=R[j])
{
A[k]=L[i];
i=i+1;
}
else
{
A[k]=R[j];
j=j+1;
}
}
return;
}
int main()
{
mrgsort m;
m.msort(m.p,m.r);
m.display();
return 0;
}