| 1 | class MergeSort |
| 2 | { |
| 3 | void merge(int arr[], int l, int m, int r) |
| 4 | { |
| 5 | int n1 = m - l + 1; |
| 6 | int n2 = r - m; |
| 7 | int L[] = new int[n1]; |
| 8 | int R[] = new int[n2]; |
| 9 | |
| 10 | /*Copy data to temp arrays*/ |
| 11 | for (int i = 0; i < n1; ++i) |
| 12 | L[i] = arr[l + i]; |
| 13 | for (int j = 0; j < n2; ++j) |
| 14 | R[j] = arr[m + 1 + j]; |
| 15 | |
| 16 | /* Merge the temp arrays */ |
| 17 | // Initial indexes of first and second subarrays |
| 18 | int i = 0, j = 0; |
| 19 | // Initial index of merged subarry array |
| 20 | int k = l; |
| 21 | while (i < n1 && j < n2) |
| 22 | { |
| 23 | if (L[i] <= R[j]) { |
| 24 | arr[k] = L[i]; |
| 25 | i++; |
| 26 | } |
| 27 | else { |
| 28 | arr[k] = R[j]; |
| 29 | j++; |
| 30 | } |
| 31 | k++; |
| 32 | } |
| 33 | |
| 34 | /* Copy remaining elements of L[] if any */ |
| 35 | while (i < n1) { |
| 36 | arr[k] = L[i]; |
| 37 | i++; |
| 38 | k++; |
| 39 | } |
| 40 | |
| 41 | /* Copy remaining elements of R[] if any */ |
| 42 | while (j < n2) { |
| 43 | arr[k] = R[j]; |
| 44 | j++; |
| 45 | k++; |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | // Main function that sorts arr[l..r] using |
| 50 | // merge() |