# In-Place Merge Sort

Implement Merge Sort i.e. standard implementation keeping the sorting algorithm as in-place.
In-place means it does not occupy extra memory for merge operation as in standard case.

Examples:

Input: arr[] = {2, 3, 4, 1}
Output: 1 2 3 4

Input: arr[] = {56, 2, 45}
Output: 2 45 56

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach:

• Maintain two pointers which point to start of the segments which have to be merged.
• Compare the elements at which the pointers are present.
• If element1 < element2 then element1 is at right position, simply increase pointer1.
• Else place element2 in its right position and all the elements at the right of element2 will be shifted right by one position. Increment all the pointers by 1.

Below is the implementation of the above approach:

## C++

 `// C++ program in-place Merge Sort ` `#include ` `using` `namespace` `std; ` ` `  `// Merges two subarrays of arr[]. ` `// First subarray is arr[l..m] ` `// Second subarray is arr[m+1..r] ` `// Inplace Implementation ` `void` `merge(``int` `arr[], ``int` `start, ``int` `mid, ``int` `end) ` `{ ` `    ``int` `start2 = mid + 1; ` ` `  `    ``// If the direct merge is already sorted ` `    ``if` `(arr[mid] <= arr[start2]) { ` `        ``return``; ` `    ``} ` ` `  `    ``// Two pointers to maintain start ` `    ``// of both arrays to merge ` `    ``while` `(start <= mid && start2 <= end) { ` ` `  `        ``// If element 1 is in right place ` `        ``if` `(arr[start] <= arr[start2]) { ` `            ``start++; ` `        ``} ` `        ``else` `{ ` `            ``int` `value = arr[start2]; ` `            ``int` `index = start2; ` ` `  `            ``// Shift all the elements between element 1 ` `            ``// element 2, right by 1. ` `            ``while` `(index != start) { ` `                ``arr[index] = arr[index - 1]; ` `                ``index--; ` `            ``} ` `            ``arr[start] = value; ` ` `  `            ``// Update all the pointers ` `            ``start++; ` `            ``mid++; ` `            ``start2++; ` `        ``} ` `    ``} ` `} ` ` `  `/* l is for left index and r is right index of the  ` `   ``sub-array of arr to be sorted */` `void` `mergeSort(``int` `arr[], ``int` `l, ``int` `r) ` `{ ` `    ``if` `(l < r) { ` ` `  `        ``// Same as (l + r) / 2, but avoids overflow ` `        ``// for large l and r ` `        ``int` `m = l + (r - l) / 2; ` ` `  `        ``// Sort first and second halves ` `        ``mergeSort(arr, l, m); ` `        ``mergeSort(arr, m + 1, r); ` ` `  `        ``merge(arr, l, m, r); ` `    ``} ` `} ` ` `  `/* UTILITY FUNCTIONS */` `/* Function to print an array */` `void` `printArray(``int` `A[], ``int` `size) ` `{ ` `    ``int` `i; ` `    ``for` `(i = 0; i < size; i++) ` `        ``printf``(``"%d "``, A[i]); ` `    ``printf``(``"\n"``); ` `} ` ` `  `/* Driver program to test above functions */` `int` `main() ` `{ ` `    ``int` `arr[] = { 12, 11, 13, 5, 6, 7 }; ` `    ``int` `arr_size = ``sizeof``(arr) / ``sizeof``(arr); ` ` `  `    ``mergeSort(arr, 0, arr_size - 1); ` ` `  `    ``printArray(arr, arr_size); ` `    ``return` `0; ` `} `

## Java

 `// Java program in-place Merge Sort ` ` `  `public` `class` `GFG{ ` ` `  `    ``// Merges two subarrays of arr[]. ` `    ``// First subarray is arr[l..m] ` `    ``// Second subarray is arr[m+1..r] ` `    ``// Inplace Implementation ` `    ``static` `void` `merge(``int` `arr[], ``int` `start, ``int` `mid, ``int` `end) ` `    ``{ ` `        ``int` `start2 = mid + ``1``; ` `     `  `        ``// If the direct merge is already sorted ` `        ``if` `(arr[mid] <= arr[start2]) { ` `            ``return``; ` `        ``} ` `     `  `        ``// Two pointers to maintain start ` `        ``// of both arrays to merge ` `        ``while` `(start <= mid && start2 <= end) { ` `     `  `            ``// If element 1 is in right place ` `            ``if` `(arr[start] <= arr[start2]) { ` `                ``start++; ` `            ``} ` `            ``else` `{ ` `                ``int` `value = arr[start2]; ` `                ``int` `index = start2; ` `     `  `                ``// Shift all the elements between element 1 ` `                ``// element 2, right by 1. ` `                ``while` `(index != start) { ` `                    ``arr[index] = arr[index - ``1``]; ` `                    ``index--; ` `                ``} ` `                ``arr[start] = value; ` `     `  `                ``// Update all the pointers ` `                ``start++; ` `                ``mid++; ` `                ``start2++; ` `            ``} ` `        ``} ` `    ``} ` `     `  `    ``/* l is for left index and r is right index of the  ` `       ``sub-array of arr to be sorted */` `    ``static` `void` `mergeSort(``int` `arr[], ``int` `l, ``int` `r) ` `    ``{ ` `        ``if` `(l < r) { ` `     `  `            ``// Same as (l + r) / 2, but avoids overflow ` `            ``// for large l and r ` `            ``int` `m = l + (r - l) / ``2``; ` `     `  `            ``// Sort first and second halves ` `            ``mergeSort(arr, l, m); ` `            ``mergeSort(arr, m + ``1``, r); ` `     `  `            ``merge(arr, l, m, r); ` `        ``} ` `    ``} ` `     `  `    ``/* UTILITY FUNCTIONS */` `    ``/* Function to print an array */` `    ``static` `void` `printArray(``int` `A[], ``int` `size) ` `    ``{ ` `        ``int` `i; ` `        ``for` `(i = ``0``; i < size; i++) ` `            ``System.out.print(A[i] + ``" "``); ` `        ``System.out.println(); ` `    ``} ` `     `  `    ``/* Driver program to test above functions */` `     ``public` `static` `void` `main(String []args){ ` `            ``int` `arr[] = { ``12``, ``11``, ``13``, ``5``, ``6``, ``7` `}; ` `            ``int` `arr_size = arr.length; ` `     `  `            ``mergeSort(arr, ``0``, arr_size - ``1``); ` `            ``printArray(arr, arr_size) ; ` `        ``} ` `    ``// This code is contributed by ANKITRAI1 ` `} `

## Python3

 `# Python program in-place Merge Sort ` ` `  `# Merges two subarrays of arr. ` `# First subarray is arr[l..m] ` `# Second subarray is arr[m+1..r] ` `# Inplace Implementation ` `def` `merge(arr, start, mid, end): ` `    ``start2 ``=` `mid ``+` `1``; ` ` `  `    ``# If the direct merge is already sorted ` `    ``if` `(arr[mid] <``=` `arr[start2]): ` `        ``return``; ` `     `  `    ``# Two pointers to maintain start ` `    ``# of both arrays to merge ` `    ``while` `(start <``=` `mid ``and` `start2 <``=` `end): ` ` `  `        ``# If element 1 is in right place ` `        ``if` `(arr[start] <``=` `arr[start2]): ` `            ``start ``+``=` `1``; ` `        ``else``: ` `            ``value ``=` `arr[start2]; ` `            ``index ``=` `start2; ` ` `  `            ``# Shift all the elements between element 1 ` `            ``# element 2, right by 1. ` `            ``while` `(index !``=` `start): ` `                ``arr[index] ``=` `arr[index ``-` `1``]; ` `                ``index ``-``=` `1``; ` `             `  `            ``arr[start] ``=` `value; ` ` `  `            ``# Update all the pointers ` `            ``start ``+``=` `1``; ` `            ``mid ``+``=` `1``; ` `            ``start2 ``+``=` `1``; ` `         `  `''' ` `* l is for left index and r is right index of ` `the sub-array of arr to be sorted ` `'''` `def` `mergeSort(arr, l, r): ` `    ``if` `(l < r): ` ` `  `        ``# Same as (l + r) / 2, but avoids overflow ` `        ``# for large l and r ` `        ``m ``=` `l ``+` `(r ``-` `l) ``/``/` `2``; ` ` `  `        ``# Sort first and second halves ` `        ``mergeSort(arr, l, m); ` `        ``mergeSort(arr, m ``+` `1``, r); ` ` `  `        ``merge(arr, l, m, r); ` `     `  `''' UTILITY FUNCTIONS '''` `''' Function to pran array '''` `def` `printArray(A, size): ` ` `  `    ``for` `i ``in` `range``(size): ` `        ``print``(A[i], end``=``" "``); ` `    ``print``(); ` ` `  `''' Driver program to test above functions '''` `if` `__name__ ``=``=` `'__main__'``: ` `    ``arr ``=` `[ ``12``, ``11``, ``13``, ``5``, ``6``, ``7` `]; ` `    ``arr_size ``=` `len``(arr); ` ` `  `    ``mergeSort(arr, ``0``, arr_size ``-` `1``); ` `    ``printArray(arr, arr_size); ` `     `  `# This code is contributed by 29AjayKumar `

## C#

 `// C# program in-place Merge Sort ` `// sum. ` `using` `System; ` ` `  `class` `GFG ` `{ ` ` `  `    ``// Merges two subarrays of arr[]. ` `    ``// First subarray is arr[l..m] ` `    ``// Second subarray is arr[m+1..r] ` `    ``// Inplace Implementation ` `    ``static` `void` `merge(``int` `[]arr, ``int` `start, ``int` `mid, ``int` `end) ` `    ``{ ` `        ``int` `start2 = mid + 1; ` `     `  `        ``// If the direct merge is already sorted ` `        ``if` `(arr[mid] <= arr[start2]) ` `        ``{ ` `            ``return``; ` `        ``} ` `     `  `        ``// Two pointers to maintain start ` `        ``// of both arrays to merge ` `        ``while` `(start <= mid && start2 <= end) ` `        ``{ ` `     `  `            ``// If element 1 is in right place ` `            ``if` `(arr[start] <= arr[start2])  ` `            ``{ ` `                ``start++; ` `            ``} ` `            ``else`  `            ``{ ` `                ``int` `value = arr[start2]; ` `                ``int` `index = start2; ` `     `  `                ``// Shift all the elements between element 1 ` `                ``// element 2, right by 1. ` `                ``while` `(index != start)  ` `                ``{ ` `                    ``arr[index] = arr[index - 1]; ` `                    ``index--; ` `                ``} ` `                ``arr[start] = value; ` `     `  `                ``// Update all the pointers ` `                ``start++; ` `                ``mid++; ` `                ``start2++; ` `            ``} ` `        ``} ` `    ``} ` `     `  `    ``/* l is for left index and r is right index of the  ` `    ``sub-array of arr to be sorted */` `    ``static` `void` `mergeSort(``int` `[]arr, ``int` `l, ``int` `r) ` `    ``{ ` `        ``if` `(l < r) ` `        ``{ ` `     `  `            ``// Same as (l + r) / 2, but avoids overflow ` `            ``// for large l and r ` `            ``int` `m = l + (r - l) / 2; ` `     `  `            ``// Sort first and second halves ` `            ``mergeSort(arr, l, m); ` `            ``mergeSort(arr, m + 1, r); ` `     `  `            ``merge(arr, l, m, r); ` `        ``} ` `    ``} ` `     `  `    ``/* UTILITY FUNCTIONS */` `    ``/* Function to print an array */` `    ``static` `void` `printArray(``int` `[]A, ``int` `size) ` `    ``{ ` `        ``int` `i; ` `        ``for` `(i = 0; i < size; i++) ` `            ``Console.Write(A[i] + ``" "``); ` `        ``Console.WriteLine(); ` `    ``} ` `     `  `    ``/* Driver code */` `    ``public` `static` `void` `Main(String []args) ` `    ``{ ` `        ``int` `[]arr = { 12, 11, 13, 5, 6, 7 }; ` `        ``int` `arr_size = arr.Length; ` ` `  `        ``mergeSort(arr, 0, arr_size - 1); ` `        ``printArray(arr, arr_size) ; ` `    ``} ` `} ` ` `  `// This code is contributed by Princi Singh `

Output:

```5 6 7 11 12 13
```

Note : Time Complexity of above approach is O(n2) because merge is O(n2). Time complexity of standard merge sort is less, O(n Log n).

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

6

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.