@@ -22,24 +22,22 @@ class MergeSort implements SortAlgorithm {
2222 @ Override
2323 @ SuppressWarnings ("unchecked" )
2424 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 );
2726 return unsorted ;
2827 }
2928
3029 /**
3130 * @param arr The array to be sorted
32- * @param temp The copy of the actual array
3331 * @param left The first index of the array
3432 * @param right The last index of the array
3533 * Recursively sorts the array in increasing order
3634 **/
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 ) {
3836 if (left < right ) {
3937 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 );
4341 }
4442
4543 }
@@ -48,36 +46,36 @@ private static <T extends Comparable<T>> void doSort(T[] arr, T[] temp, int left
4846 * This method implements the merge step of the merge sort
4947 *
5048 * @param arr The array to be sorted
51- * @param temp The copy of the actual array
5249 * @param left The first index of the array
5350 * @param mid The middle index of the array
5451 * @param right The last index of the array
5552 * merges two parts of an array in increasing order
5653 **/
5754
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 ];
6258 int i = left ;
6359 int j = mid + 1 ;
64- int k = left ;
60+ int k = 0 ;
6561
6662 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 ++];
6965 } else {
70- arr [k ++] = temp [j ++];
66+ temp [k ++] = arr [j ++];
7167 }
7268 }
7369
7470 while (i <= mid ) {
75- arr [k ++] = temp [i ++];
71+ temp [k ++] = arr [i ++];
7672 }
7773
7874 while (j <= right ) {
79- arr [k ++] = temp [j ++];
75+ temp [k ++] = arr [j ++];
8076 }
77+
78+ System .arraycopy (temp , 0 , arr , left , length );
8179 }
8280
8381 // Driver program
0 commit comments