@@ -22,24 +22,22 @@ class MergeSort implements SortAlgorithm {
22
22
@ Override
23
23
@ SuppressWarnings ("unchecked" )
24
24
public <T extends Comparable <T >> T [] sort (T [] unsorted ) {
25
- T [] tmp = (T []) new Comparable [unsorted .length ];
26
- doSort (unsorted , tmp , 0 , unsorted .length - 1 );
25
+ doSort (unsorted , 0 , unsorted .length - 1 );
27
26
return unsorted ;
28
27
}
29
28
30
29
/**
31
30
* @param arr The array to be sorted
32
- * @param temp The copy of the actual array
33
31
* @param left The first index of the array
34
32
* @param right The last index of the array
35
33
* Recursively sorts the array in increasing order
36
34
**/
37
- private static <T extends Comparable <T >> void doSort (T [] arr , T [] temp , int left , int right ) {
35
+ private static <T extends Comparable <T >> void doSort (T [] arr , int left , int right ) {
38
36
if (left < right ) {
39
37
int mid = left + (right - left ) / 2 ;
40
- doSort (arr , temp , left , mid );
41
- doSort (arr , temp , mid + 1 , right );
42
- merge (arr , temp , left , mid , right );
38
+ doSort (arr , left , mid );
39
+ doSort (arr , mid + 1 , right );
40
+ merge (arr , left , mid , right );
43
41
}
44
42
45
43
}
@@ -48,36 +46,36 @@ private static <T extends Comparable<T>> void doSort(T[] arr, T[] temp, int left
48
46
* This method implements the merge step of the merge sort
49
47
*
50
48
* @param arr The array to be sorted
51
- * @param temp The copy of the actual array
52
49
* @param left The first index of the array
53
50
* @param mid The middle index of the array
54
51
* @param right The last index of the array
55
52
* merges two parts of an array in increasing order
56
53
**/
57
54
58
- private static <T extends Comparable <T >> void merge (T [] arr , T [] temp , int left , int mid , int right ) {
59
- System .arraycopy (arr , left , temp , left , right - left + 1 );
60
-
61
-
55
+ private static <T extends Comparable <T >> void merge (T [] arr , int left , int mid , int right ) {
56
+ int length = right - left + 1 ;
57
+ T [] temp = (T []) new Comparable [length ];
62
58
int i = left ;
63
59
int j = mid + 1 ;
64
- int k = left ;
60
+ int k = 0 ;
65
61
66
62
while (i <= mid && j <= right ) {
67
- if (temp [i ].compareTo (temp [j ]) <= 0 ) {
68
- arr [k ++] = temp [i ++];
63
+ if (arr [i ].compareTo (arr [j ]) <= 0 ) {
64
+ temp [k ++] = arr [i ++];
69
65
} else {
70
- arr [k ++] = temp [j ++];
66
+ temp [k ++] = arr [j ++];
71
67
}
72
68
}
73
69
74
70
while (i <= mid ) {
75
- arr [k ++] = temp [i ++];
71
+ temp [k ++] = arr [i ++];
76
72
}
77
73
78
74
while (j <= right ) {
79
- arr [k ++] = temp [j ++];
75
+ temp [k ++] = arr [j ++];
80
76
}
77
+
78
+ System .arraycopy (temp , 0 , arr , left , length );
81
79
}
82
80
83
81
// Driver program
0 commit comments