Merge Sort with O(1) extra space merge and O(n lg n) time [Unsigned Integers Only]

06 Jul, 2021
We have discussed Merge sort. How to modify the algorithm so that merge works in O(1) extra space and algorithm still works in O(n Log n) time. We may assume that the input values are integers only.
Examples: 
Input : 5 4 3 2 1
Output : 1 2 3 4 5

Input : 999 612 589 856 56 945 243
Output : 56 243 589 612 856 945 999
For integer types, merge sort can be made inplace using some mathematics trick of modulus and division. That means storing two elements value at one index and can be extracted using modulus and division. 
First we have to find a value greater than all the elements of the array. Now we can store the original value as modulus and the second value as division. Suppose we want to store arr[i] and arr[j] both at index i(means in arr[i]). First we have to find a ‘maxval’ greater than both arr[i] and arr[j]. Now we can store as arr[i] = arr[i] + arr[j]*maxval. Now arr[i]%maxval will give the original value of arr[i] and arr[i]/maxval will give the value of arr[j]. So below is the implementation on merge sort.
Approach: (Euclidean Division)
                                           dividend = divisor * quotient +remainder
ex: 5/3 = q:1, r:2    applying euclidean: 3*1+2 =>5 (dividend)
divisor = maxele (absolute max element in the array)+1 (so that we always get non zero remainder)quotient = min(first, second)remainder = original element
Note: (when getting current element, assume the current container already has encoded element hence using % divisor)first = arr[i] % divisorsecond = arr[j] % divisor 
encoded element = remainder + quotient*divisor
Possible issues in Merging:
1. If current number is Integer.MAX then new encoded value which is usually greater than current element will cause integer overflow and data corruption (In python there is no limit to number size so this issue will not occur).
2. Doesn’t handle negative numbers (ie, when encoding a -ve number(current) with another -ve number(chosen smallest) the sign can’t be preserved since both numbers have -ve sign. Also absolute values must be used when computing dividend = divisor*quotient+remainder (divisor = maxele, quotient = smallest, remainder = original) and sign must be restored, still it might not work due to sign preservation issue.
3. Only applicable to Unsigned integers, like indexes which are usually non-negative.
4. AUX = O(n) in worst case, assuming in a language like python where there is no limit to word/integer size, when input array elements are almost at Integer.MAX, then encoded value will require possibly 2x bits space to represent new number, the 2x bit space on whole can become +1x array size, which is almost like creating an AUX array but in an indirect way.
5. mod and division operations are the costliest, hence reduces overall performance(upto some extent).
C++
Java
Python3
C#
Javascript
// C++ program to sort an array using merge sort such// that merge operation takes O(1) extra space.#include <bits/stdc++.h>using namespace std;void merge(int arr[], int beg, int mid, int end, int maxele){    int i = beg;    int j = mid + 1;    int k = beg;    while (i <= mid && j <= end) {        if (arr[i] % maxele <= arr[j] % maxele) {            arr[k] = arr[k] + (arr[i] % maxele) * maxele;            k++;            i++;        }        else {            arr[k] = arr[k] + (arr[j] % maxele) * maxele;            k++;            j++;        }    }    while (i <= mid) {        arr[k] = arr[k] + (arr[i] % maxele) * maxele;        k++;        i++;    }    while (j <= end) {        arr[k] = arr[k] + (arr[j] % maxele) * maxele;        k++;        j++;    }     // Obtaining actual values    for (int i = beg; i <= end; i++)        arr[i] = arr[i] / maxele;} // Recursive merge sort with extra parameter, naxelevoid mergeSortRec(int arr[], int beg, int end, int maxele){    if (beg < end) {        int mid = (beg + end) / 2;        mergeSortRec(arr, beg, mid, maxele);        mergeSortRec(arr, mid + 1, end, maxele);        merge(arr, beg, mid, end, maxele);    }} // This functions finds max element and calls recursive// merge sort.void mergeSort(int arr[], int n){   int maxele = *max_element(arr, arr+n) + 1;   mergeSortRec(arr, 0, n-1, maxele);} int main(){    int arr[] = { 999, 612, 589, 856, 56, 945, 243 };    int n = sizeof(arr) / sizeof(arr[0]);         mergeSort(arr, n);     cout << "Sorted array \n";    for (int i = 0; i < n; i++)        cout << arr[i] << " ";    return 0;}
// Java program to sort an array// using merge sort such that// merge operation takes O(1)// extra space.import java.util.Arrays; class GFG{     static void merge(int[] arr, int beg,                        int mid, int end,                        int maxele)    {        int i = beg;        int j = mid + 1;        int k = beg;        while (i <= mid && j <= end)        {            if (arr[i] % maxele <=                arr[j] % maxele)            {                arr[k] = arr[k] + (arr[i]                        % maxele) * maxele;                k++;                i++;            }            else            {                arr[k] = arr[k] +                        (arr[j] % maxele)                        * maxele;                k++;                j++;            }        }        while (i <= mid)        {            arr[k] = arr[k] + (arr[i]                    % maxele) * maxele;            k++;            i++;        }        while (j <= end)        {            arr[k] = arr[k] + (arr[j]                    % maxele) * maxele;            k++;            j++;        }         // Obtaining actual values        for (i = beg; i <= end; i++)        {            arr[i] = arr[i] / maxele;        }    }     // Recursive merge sort    // with extra parameter, naxele    static void mergeSortRec(int[] arr, int beg,            int end, int maxele)    {        if (beg < end)        {            int mid = (beg + end) / 2;            mergeSortRec(arr, beg,                        mid, maxele);            mergeSortRec(arr, mid + 1,                        end, maxele);            merge(arr, beg, mid,                    end, maxele);        }    }     // This functions finds    // max element and calls    // recursive merge sort.    static void mergeSort(int[] arr, int n)    {        int maxele = Arrays.stream(arr).max().getAsInt() + 1;        mergeSortRec(arr, 0, n - 1, maxele);    }     // Driver code    public static void main(String[] args)    {         int[] arr = {999, 612, 589,                    856, 56, 945, 243};        int n = arr.length;         mergeSort(arr, n);         System.out.println("Sorted array ");        for (int i = 0; i < n; i++)        {            System.out.print(arr[i] + " ");        }    }} // This code is contributed by 29AjayKumar
# Python3 program to sort an array using# merge sort such that merge operation# takes O(1) extra space.def merge(arr, beg, mid, end, maxele):         i = beg    j = mid + 1    k = beg         while (i <= mid and j <= end):        if (arr[i] % maxele <= arr[j] % maxele):            arr[k] = arr[k] + (arr[i] %                    maxele) * maxele            k += 1            i += 1        else:            arr[k] = arr[k] + (arr[j] %                    maxele) * maxele            k += 1            j += 1                 while (i <= mid):        arr[k] = arr[k] + (arr[i] %                maxele) * maxele        k += 1        i += 1    while (j <= end):        arr[k] = arr[k] + (arr[j] %                maxele) * maxele        k += 1        j += 1     # Obtaining actual values    for i in range(beg, end + 1):        arr[i] = arr[i] // maxele # Recursive merge sort with extra# parameter, naxeledef mergeSortRec(arr, beg, end, maxele):         if (beg < end):        mid = (beg + end) // 2        mergeSortRec(arr, beg, mid, maxele)        mergeSortRec(arr, mid + 1, end, maxele)        merge(arr, beg, mid, end, maxele) # This functions finds max element and# calls recursive merge sort.def mergeSort(arr, n):        maxele = max(arr) + 1   mergeSortRec(arr, 0, n - 1, maxele) # Driver Codeif __name__ == '__main__':     arr = [ 999, 612, 589, 856, 56, 945, 243 ]    n =  len(arr)    mergeSort(arr, n)     print("Sorted array")         for i in range(n):        print(arr[i], end = " ") # This code is contributed by mohit kumar 29
// C# program to sort an array// using merge sort such that// merge operation takes O(1)// extra space.using System;using System.Linq; class GFG{static void merge(int []arr, int beg,                  int mid, int end,                  int maxele){    int i = beg;    int j = mid + 1;    int k = beg;    while (i <= mid && j <= end)    {        if (arr[i] %            maxele <= arr[j] % maxele)        {            arr[k] = arr[k] + (arr[i] %                     maxele) * maxele;            k++;            i++;        }        else        {            arr[k] = arr[k] +                    (arr[j] % maxele) *                              maxele;            k++;            j++;        }    }    while (i <= mid)    {        arr[k] = arr[k] + (arr[i] %                 maxele) * maxele;        k++;        i++;    }    while (j <= end)    {        arr[k] = arr[k] + (arr[j] %                 maxele) * maxele;        k++;        j++;    }     // Obtaining actual values    for ( i = beg; i <= end; i++)        arr[i] = arr[i] / maxele;} // Recursive merge sort// with extra parameter, naxelestatic void mergeSortRec(int []arr, int beg,                         int end, int maxele){    if (beg < end)    {        int mid = (beg + end) / 2;        mergeSortRec(arr, beg,                     mid, maxele);        mergeSortRec(arr, mid + 1,                     end, maxele);        merge(arr, beg, mid,              end, maxele);    }} // This functions finds// max element and calls// recursive merge sort.static void mergeSort(int []arr, int n){    int maxele = arr.Max() + 1;    mergeSortRec(arr, 0, n - 1, maxele);} //Driver codepublic static void Main (){    int []arr = {999, 612, 589,                 856, 56, 945, 243};    int n = arr.Length;     mergeSort(arr, n);     Console.WriteLine("Sorted array ");    for (int i = 0; i < n; i++)        Console.Write( arr[i] + " ");}} // This code is contributed// by inder_verma.
<script>// Javascript program to sort an array// using merge sort such that// merge operation takes O(1)// extra space.            function merge(arr,beg,mid,end,maxele)    {        let i = beg;        let j = mid + 1;        let k = beg;        while (i <= mid && j <= end)        {            if (arr[i] % maxele <=                arr[j] % maxele)            {                arr[k] = arr[k] + (arr[i]                        % maxele) * maxele;                k++;                i++;            }            else            {                arr[k] = arr[k] +                        (arr[j] % maxele)                        * maxele;                k++;                j++;            }        }        while (i <= mid)        {            arr[k] = arr[k] + (arr[i]                    % maxele) * maxele;            k++;            i++;        }        while (j <= end)        {            arr[k] = arr[k] + (arr[j]                    % maxele) * maxele;            k++;            j++;        }          // Obtaining actual values        for (i = beg; i <= end; i++)        {            arr[i] = Math.floor(arr[i] / maxele);        }    }         // Recursive merge sort    // with extra parameter, naxele    function mergeSortRec(arr,beg,end,maxele)    {        if (beg < end)        {            let mid = Math.floor((beg + end) / 2);            mergeSortRec(arr, beg,                        mid, maxele);            mergeSortRec(arr, mid + 1,                        end, maxele);            merge(arr, beg, mid,                    end, maxele);        }    }         // This functions finds    // max element and calls    // recursive merge sort.    function  mergeSort(arr,n)    {        let maxele = Math.max(...arr) + 1;        mergeSortRec(arr, 0, n - 1, maxele);         }         // Driver code    let arr=[999, 612, 589,                    856, 56, 945, 243];                         let n = arr.length;    mergeSort(arr, n);         document.write("Sorted array <br>");    for (let i = 0; i < n; i++)        {            document.write(arr[i] + " ");        }     // This code is contributed by patel2127</script>
Sorted array 
56 243 589 612 856 945 999
 
inderDuMCA
29AjayKumar
mohit kumar 29
patel2127
mahee96
Merge Sort
Modular Arithmetic
Divide and Conquer
Mathematical
Sorting
Mathematical
Divide and Conquer
Sorting
Modular Arithmetic
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.