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

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

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


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 Log n) because merge is O(n2). Time complexity of standard merge sort is less, O(n Log n).



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.