1
+ /**
2
+ * MergeSort.java
3
+ * This program implements the Merge Sort algorithm using recursion.
4
+ * Time Complexity: O(n log n)
5
+ */
6
+
7
+ public class MergeSort {
8
+
9
+ // Method to recursively divide and sort the array
10
+ public static void mergeSort (int [] arr , int left , int right ) {
11
+ if (left < right ) {
12
+ int mid = (left + right ) / 2 ;
13
+
14
+ // Recursively sort the left half
15
+ mergeSort (arr , left , mid );
16
+
17
+ // Recursively sort the right half
18
+ mergeSort (arr , mid + 1 , right );
19
+
20
+ // Merge the two sorted halves
21
+ merge (arr , left , mid , right );
22
+ }
23
+ }
24
+
25
+ // Method to merge two sorted halves
26
+ public static void merge (int [] arr , int left , int mid , int right ) {
27
+ // Sizes of subarrays
28
+ int n1 = mid - left + 1 ;
29
+ int n2 = right - mid ;
30
+
31
+ // Temp arrays
32
+ int [] L = new int [n1 ];
33
+ int [] R = new int [n2 ];
34
+
35
+ // Copy data to temp arrays
36
+ for (int i = 0 ; i < n1 ; ++i )
37
+ L [i ] = arr [left + i ];
38
+ for (int j = 0 ; j < n2 ; ++j )
39
+ R [j ] = arr [mid + 1 + j ];
40
+
41
+ // Merge temp arrays back into arr
42
+ int i = 0 , j = 0 , k = left ;
43
+ while (i < n1 && j < n2 ) {
44
+ if (L [i ] <= R [j ]) {
45
+ arr [k ++] = L [i ++];
46
+ } else {
47
+ arr [k ++] = R [j ++];
48
+ }
49
+ }
50
+
51
+ // Copy remaining elements of L[]
52
+ while (i < n1 )
53
+ arr [k ++] = L [i ++];
54
+
55
+ // Copy remaining elements of R[]
56
+ while (j < n2 )
57
+ arr [k ++] = R [j ++];
58
+ }
59
+
60
+ public static void main (String [] args ) {
61
+ int [] arr = {38 , 27 , 43 , 3 , 9 , 82 , 10 };
62
+ mergeSort (arr , 0 , arr .length - 1 );
63
+
64
+ System .out .println ("Sorted array:" );
65
+ for (int value : arr ) {
66
+ System .out .print (value + " " );
67
+ }
68
+ }
69
+ }
0 commit comments