Skip to content
Related Articles

Related Articles

In-Place Merge Sort
  • Difficulty Level : Hard
  • Last Updated : 02 Feb, 2021

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 

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 shift all the elements between element1 and element2(including element1 but excluding element2) right by 1 and then place the element2 in the previous place(i.e. before shifting right) of element1. Increment all the pointers by 1.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program in-place Merge Sort
#include <bits/stdc++.h>
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[0]);
 
    mergeSort(arr, 0, arr_size - 1);
 
    printArray(arr, arr_size);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


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
Recommended Articles
Page :