File tree Expand file tree Collapse file tree 1 file changed +76
-0
lines changed Expand file tree Collapse file tree 1 file changed +76
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < cmath>
3
+ using namespace std ;
4
+ void merge (int A[],int p,int q,int r)
5
+ {
6
+ int i,j,x,y;
7
+ int n1=q-p+1 ;int n2=r-q;
8
+ int B[n1],C[n2];
9
+ for (i=0 ;i<n1;i++)
10
+ {
11
+ B[i]=A[p+i];
12
+ }
13
+ for (x=0 ;x<n2;x++)
14
+ {
15
+ C[x]=A[q+1 +x];
16
+ }int k;
17
+ i = 0 ; // Initial index of first subarray
18
+ j = 0 ; // Initial index of second subarray
19
+ k = p; // Initial index of merged subarray
20
+ while (i < n1 && j < n2)
21
+ {
22
+ if (B[i] <= C[j])
23
+ {
24
+ A[k] = B[i];
25
+ i++;
26
+ }
27
+ else
28
+ {
29
+ A[k] = C[j];
30
+ j++;
31
+ }
32
+ k++;
33
+ }
34
+
35
+ while (i < n1)
36
+ {
37
+ A[k] = B[i];
38
+ i++;
39
+ k++;
40
+ }
41
+
42
+ while (j < n2)
43
+ {
44
+ A[k] = C[j];
45
+ j++;
46
+ k++;
47
+ }
48
+ }
49
+
50
+
51
+
52
+ void mergesort (int A[],int p,int r)
53
+ {int q;
54
+ if (p>=r)
55
+ {
56
+ return ;
57
+ }
58
+ else
59
+ {
60
+ q=(p+r)/2 ;
61
+ mergesort (A,p,q);
62
+ mergesort (A,q+1 ,r);
63
+ merge (A,p,q,r);
64
+ }
65
+ }
66
+
67
+ int main ()
68
+ {
69
+ int A[5 ],a;
70
+ for (a=0 ;a<5 ;a++)
71
+ cin>>A[a];
72
+ mergesort (A,0 ,4 );
73
+ for (a=0 ;a<5 ;a++)
74
+ cout<<A[a]<<" " ;
75
+
76
+ }
You can’t perform that action at this time.
0 commit comments