1+ /**
2+ * Merge Sort - Space Optimized Implementation
3+ *
4+ * 📌 Concept:
5+ * Same Divide and Conquer approach as basic Merge Sort,
6+ * but optimized to avoid repeated creation of temporary arrays.
7+ *
8+ * 🔥 Optimization:
9+ * Instead of creating a new temp array in every merge call,
10+ * we create a single temp array once and reuse it.
11+ *
12+ * 📊 Time Complexity:
13+ * Best Case : O(n log n)
14+ * Average Case: O(n log n)
15+ * Worst Case : O(n log n)
16+ *
17+ * 📦 Space Complexity:
18+ * O(n) - but avoids repeated allocations (more efficient in practice)
19+ *
20+ * ✅ Stable Sorting Algorithm
21+ */
22+ public class MergeSortOptimized {
23+
24+ public static void main (String [] args ) {
25+ int [] arr = {38 , 27 , 43 , 3 , 9 , 82 , 10 };
26+
27+ System .out .println ("Before Sorting:" );
28+ printArray (arr );
29+
30+ // Create temp array once
31+ int [] temp = new int [arr .length ];
32+
33+ mergeSort (arr , temp , 0 , arr .length - 1 );
34+
35+ System .out .println ("After Sorting:" );
36+ printArray (arr );
37+ }
38+
39+ /**
40+ * Recursive divide function
41+ */
42+ public static void mergeSort (int [] arr , int [] temp , int left , int right ) {
43+
44+ if (left >= right ) {
45+ return ;
46+ }
47+
48+ int mid = left + (right - left ) / 2 ;
49+
50+ // Divide
51+ mergeSort (arr , temp , left , mid );
52+ mergeSort (arr , temp , mid + 1 , right );
53+
54+ // Merge using shared temp array
55+ merge (arr , temp , left , mid , right );
56+ }
57+
58+ /**
59+ * Merge function using reusable temp array
60+ */
61+ private static void merge (int [] arr , int [] temp , int left , int mid , int right ) {
62+
63+ int i = left ; // left half pointer
64+ int j = mid + 1 ; // right half pointer
65+ int k = left ; // temp array index (same indexing)
66+
67+ // Merge both halves into temp[]
68+ while (i <= mid && j <= right ) {
69+
70+ if (arr [i ] <= arr [j ]) {
71+ temp [k ++] = arr [i ++];
72+ } else {
73+ temp [k ++] = arr [j ++];
74+ }
75+ }
76+
77+ // Copy remaining elements of left half
78+ while (i <= mid ) {
79+ temp [k ++] = arr [i ++];
80+ }
81+
82+ // Copy remaining elements of right half
83+ while (j <= right ) {
84+ temp [k ++] = arr [j ++];
85+ }
86+
87+ // Copy back from temp[] to original array
88+ for (int p = left ; p <= right ; p ++) {
89+ arr [p ] = temp [p ];
90+ }
91+ }
92+
93+ /**
94+ * Utility method to print array
95+ */
96+ private static void printArray (int [] arr ) {
97+ for (int num : arr ) {
98+ System .out .print (num + " " );
99+ }
100+ System .out .println ();
101+ }
102+ }
0 commit comments