@@ -23,25 +23,25 @@ public int[] sort(int[] sourceArray) throws Exception {
2323
2424 protected int [] merge (int [] left , int [] right ) {
2525 int [] result = new int [left .length + right .length ];
26- int i = 0 ;
27- while (left .length > 0 && right .length > 0 ) {
28- if (left [0 ] <= right [0 ]) {
29- result [i ++] = left [0 ];
30- left = Arrays .copyOfRange (left , 1 , left .length );
26+ int l = 0 , r = 0 , len = 0 ;
27+ while (len < left .length + right .length ) {
28+ if (left [l ] <= right [r ]) {
29+ result [len ++] = left [l ++];
30+
31+ if (l == left .length ) {
32+ for (int i = r ; i < right .length ; i ++) {
33+ result [len ++] = right [r ++];
34+ }
35+ }
3136 } else {
32- result [i ++] = right [0 ];
33- right = Arrays .copyOfRange (right , 1 , right .length );
34- }
35- }
37+ result [len ++] = right [r ++];
3638
37- while (left .length > 0 ) {
38- result [i ++] = left [0 ];
39- left = Arrays .copyOfRange (left , 1 , left .length );
40- }
41-
42- while (right .length > 0 ) {
43- result [i ++] = right [0 ];
44- right = Arrays .copyOfRange (right , 1 , right .length );
39+ if (r == right .length ) {
40+ for (int i = l ; i < left .length ; i ++) {
41+ result [len ++] = left [l ++];
42+ }
43+ }
44+ }
4545 }
4646
4747 return result ;
0 commit comments