@@ -115,7 +115,8 @@ public static void insertionSort(int[] array) {
115
115
116
116
/* Move elements of arr[0..i-1], that are
117
117
greater than key, to one position ahead
118
- of their current position */
118
+ of their current position
119
+ searching and shift at once */
119
120
while (j >= 0 && array [j ] > array [i ]) {
120
121
// using rotate by condition(array[j] > key), no swap, since shifting has better performance than swap
121
122
array [j + 1 ] = array [j ];
@@ -331,6 +332,49 @@ else if (aux[j] < aux[i])
331
332
}
332
333
333
334
335
+ ////////////////////////////// Merge Sort ////////////////////////
336
+ public static int [] modularMergeSort (int [] array ) {
337
+ return modularMergeSort (array , 0 , array .length - 1 );
338
+ }
339
+ private static int [] modularMergeSort (int [] array , int start , int end ) {
340
+ if (start == end )
341
+ return new int [] {array [start ]};
342
+ int mid = start + (end - start ) / 2 ;
343
+ int [] leftArray = modularMergeSort (array , start , mid );
344
+ int [] rightArray = modularMergeSort (array , mid + 1 , end );
345
+ return myMerge (leftArray , rightArray );
346
+ }
347
+
348
+ private static int [] myMerge (int [] leftArray , int [] rightArray ) {
349
+ int length = leftArray .length + rightArray .length ;
350
+ int [] mergedArray = new int [length ];
351
+
352
+ int i = 0 , j = 0 , k = 0 ;
353
+ for (; k < length - 1 && i < leftArray .length && j < rightArray .length ; k ++) {
354
+ if (leftArray [i ] <= rightArray [j ]) {
355
+ mergedArray [k ] = leftArray [i ];
356
+ i ++;
357
+ } else {
358
+ mergedArray [k ] = rightArray [j ];
359
+ j ++;
360
+ }
361
+ }
362
+
363
+ if (i == leftArray .length ) {
364
+ for (; j < rightArray .length ; j ++) {
365
+ mergedArray [k ] = rightArray [j ];
366
+ k ++;
367
+ }
368
+ } else if (j == rightArray .length ) {
369
+ for (; i < leftArray .length ; i ++) {
370
+ mergedArray [k ] = leftArray [i ];
371
+ k ++;
372
+ }
373
+ }
374
+ return mergedArray ;
375
+ }
376
+ ////////////////////////////// Merge Sort ////////////////////////
377
+
334
378
/**
335
379
* In quick sort we pick a random element and partition the array, such that all numbers that are less than the
336
380
* partitioning element come before all elements that are greater than it. The partitioning can be performed
0 commit comments