1
+ class MergeSort
2
+ {
3
+ // Merges two subarrays of arr[].
4
+ // First subarray is arr[l..m]
5
+ // Second subarray is arr[m+1..r]
6
+ void merge (int arr [], int l , int m , int r )
7
+ {
8
+ // Find sizes of two subarrays to be merged
9
+ int n1 = m - l + 1 ;
10
+ int n2 = r - m ;
11
+
12
+ /* Create temp arrays */
13
+ int L [] = new int [n1 ];
14
+ int R [] = new int [n2 ];
15
+
16
+ /*Copy data to temp arrays*/
17
+ for (int i =0 ; i <n1 ; ++i )
18
+ L [i ] = arr [l + i ];
19
+ for (int j =0 ; j <n2 ; ++j )
20
+ R [j ] = arr [m + 1 + j ];
21
+
22
+
23
+ /* Merge the temp arrays */
24
+
25
+ // Initial indexes of first and second subarrays
26
+ int i = 0 , j = 0 ;
27
+
28
+ // Initial index of merged subarry array
29
+ int k = l ;
30
+ while (i < n1 && j < n2 )
31
+ {
32
+ if (L [i ] <= R [j ])
33
+ {
34
+ arr [k ] = L [i ];
35
+ i ++;
36
+ }
37
+ else
38
+ {
39
+ arr [k ] = R [j ];
40
+ j ++;
41
+ }
42
+ k ++;
43
+ }
44
+
45
+ /* Copy remaining elements of L[] if any */
46
+ while (i < n1 )
47
+ {
48
+ arr [k ] = L [i ];
49
+ i ++;
50
+ k ++;
51
+ }
52
+
53
+ /* Copy remaining elements of R[] if any */
54
+ while (j < n2 )
55
+ {
56
+ arr [k ] = R [j ];
57
+ j ++;
58
+ k ++;
59
+ }
60
+ }
61
+
62
+ // Main function that sorts arr[l..r] using
63
+ // merge()
64
+ void sort (int arr [], int l , int r )
65
+ {
66
+ if (l < r )
67
+ {
68
+ // Find the middle point
69
+ int m = (l +r )/2 ;
70
+
71
+ // Sort first and second halves
72
+ sort (arr , l , m );
73
+ sort (arr , m +1 , r );
74
+
75
+ // Merge the sorted halves
76
+ merge (arr , l , m , r );
77
+ }
78
+ }
79
+
80
+ /* A utility function to print array of size n */
81
+ static void printArray (int arr [])
82
+ {
83
+ int n = arr .length ;
84
+ for (int i =0 ; i <n ; ++i )
85
+ System .out .print (arr [i ] + " " );
86
+ System .out .println ();
87
+ }
88
+
89
+ // Driver method
90
+ public static void main (String args [])
91
+ {
92
+ int arr [] = {12 , 11 , 13 , 5 , 6 , 7 };
93
+
94
+ System .out .println ("Given Array" );
95
+ printArray (arr );
96
+
97
+ MergeSort ob = new MergeSort ();
98
+ ob .sort (arr , 0 , arr .length -1 );
99
+
100
+ System .out .println ("\n Sorted array" );
101
+ printArray (arr );
102
+ }
103
+ }
0 commit comments