forked from rohitsh16/CP_mathematics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmergesort.cpp
75 lines (67 loc) · 926 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include<iostream>
#include<cmath>
using namespace std;
void merge(int A[],int p,int q,int r)
{
int i,j,x,y;
int n1=q-p+1;int n2=r-q;
int B[n1],C[n2];
for(i=0;i<n1;i++)
{
B[i]=A[p+i];
}
for(x=0;x<n2;x++)
{
C[x]=A[q+1+x];
}int k;
i = 0,j = 0,k = p;
while (i < n1 && j < n2)
{
if (B[i] <= C[j])
{
A[k] = B[i];
i++;
}
else
{
A[k] = C[j];
j++;
}
k++;
}
while (i < n1)
{
A[k] = B[i];
i++;
k++;
}
while (j < n2)
{
A[k] = C[j];
j++;
k++;
}
}
void mergesort(int A[],int p,int r)
{int q;
if(p>=r)
{
return;
}
else
{
q=(p+r)/2;
mergesort(A,p,q);
mergesort(A,q+1,r);
merge(A,p,q,r);
}
}
int main()
{
int A[5],a;
for(a=0;a<5;a++)
cin>>A[a];
mergesort(A,0,4);
for(a=0;a<5;a++)
cout<<A[a]<<" ";
}