Implement Merge-sort in-place

Pattern: Basic sorts

easy

Merge sort without a temporary array. When a right-half value belongs earlier, shift the left block one place and drop it in.

The problem

You are given an array of between 1 and 1000 whole numbers. Sort it in increasing order with merge sort, but without allocating a temporary array for merging, and return it. For example, [5, 2, 4, 1] becomes [1, 2, 4, 5].

This problem is from Love Babbar's 450 sheet. Its main link points to GeeksforGeeks, which this site has not been able to check automatically. The function name mergeSortInPlace and the limits are this guide's own.

Think first

  • Ordinary merge sort copies into a new list while merging. Where else could the smaller value go?
  • If nums[right] must come before nums[left], which values have to move to make room, and how far?
  • What does that cost when many values from the right belong at the front?

Hints

    Brute force, and why it fails

    Normal merge sort is O(n log n) and uses O(n) extra memory for merging. Insertion sort is in place but O(n²). This version is in place too. Its shifting can cost up to O(n) per element, so the worst case is O(n²), but it keeps merge sort's structure and uses only the recursion stack.

    The key insight

    A merge can be done inside the array if, each time a right-half value must jump ahead, the block in between slides one place to make room. Memory drops to O(1) per merge at the price of extra shifting.

    Dry run

    20left
    51 
    12right
    43 
    mid1

    The two halves [2, 5] and [1, 4] are each sorted and sit side by side. left points at 2 and right at 1.

    Step 1 of 5

    The plan

    function mergeInPlace(nums, left, mid, high):
        right = mid + 1
        while left <= mid and right <= high:
            if nums[left] <= nums[right]:
                left = left + 1                     # already in place
            else:
                value = nums[right]
                shift nums[left..right-1] one place to the right
                nums[left] = value
                left = left + 1
                mid = mid + 1                       # the left run moved right
                right = right + 1
    

    The sort itself is ordinary merge sort calling mergeInPlace instead of a copying merge.

    Complexity

    Time
    O(n²) worst case
    Space
    O(log n)

    Each value taken from the right can shift up to the whole left run. In the worst case that adds up to O(n²) moves. No temporary array is used, only the O(log n) recursion stack.

    Edge cases

    • One element: nothing to merge.
    • Halves already in order (the last left value is no bigger than the first right value): left walks to mid and nothing moves.
    • Every right value smaller than every left value: each one shifts the whole left run, which is the worst case.
    • Equal values stay in order because of <=.
    I've built my logic, show the code

    Java

    class Solution {
        public int[] mergeSortInPlace(int[] nums) {
            sort(nums, 0, nums.length - 1);
            return nums;
        }
    
        private void sort(int[] nums, int low, int high) {
            if (low >= high) {
                return;
            }
            int mid = low + (high - low) / 2;
            sort(nums, low, mid);
            sort(nums, mid + 1, high);
            mergeInPlace(nums, low, mid, high);
        }
    
        private void mergeInPlace(int[] nums, int left, int mid, int high) {
            int right = mid + 1;
            while (left <= mid && right <= high) {
                if (nums[left] <= nums[right]) {
                    left++;                             // already in place
                } else {
                    int value = nums[right];            // nums[right] belongs before nums[left]
                    for (int k = right; k > left; k--) {
                        nums[k] = nums[k - 1];          // shift the block nums[left..right-1] one place right
                    }
                    nums[left] = value;
                    left++;
                    mid++;                              // the left run moved one place right
                    right++;
                }
            }
        }
    }

    C++

    class Solution {
    public:
        vector<int> mergeSortInPlace(vector<int>& nums) {
            sort(nums, 0, static_cast<int>(nums.size()) - 1);
            return nums;
        }
    
        void sort(vector<int>& nums, int low, int high) {
            if (low >= high) {
                return;
            }
            int mid = low + (high - low) / 2;
            sort(nums, low, mid);
            sort(nums, mid + 1, high);
            mergeInPlace(nums, low, mid, high);
        }
    
        void mergeInPlace(vector<int>& nums, int left, int mid, int high) {
            int right = mid + 1;
            while (left <= mid && right <= high) {
                if (nums[left] <= nums[right]) {
                    left++;                             // already in place
                } else {
                    int value = nums[right];            // nums[right] belongs before nums[left]
                    for (int k = right; k > left; k--) {
                        nums[k] = nums[k - 1];          // shift the block nums[left..right-1] one place right
                    }
                    nums[left] = value;
                    left++;
                    mid++;                              // the left run moved one place right
                    right++;
                }
            }
        }
    };

    Python

    class Solution:
        def mergeSortInPlace(self, nums):
            self.sort(nums, 0, len(nums) - 1)
            return nums
    
        def sort(self, nums, low, high):
            if low >= high:
                return
            mid = (low + high) // 2
            self.sort(nums, low, mid)
            self.sort(nums, mid + 1, high)
            self.mergeInPlace(nums, low, mid, high)
    
        def mergeInPlace(self, nums, left, mid, high):
            right = mid + 1
            while left <= mid and right <= high:
                if nums[left] <= nums[right]:
                    left += 1                           # already in place
                else:
                    value = nums[right]                 # nums[right] belongs before nums[left]
                    for k in range(right, left, -1):
                        nums[k] = nums[k - 1]           # shift the block nums[left..right-1] one place right
                    nums[left] = value
                    left += 1
                    mid += 1                            # the left run moved one place right
                    right += 1

    Common mistakes

    • Forgetting to move mid after a shift, so the loop compares against stale positions.
    • Shifting from left to right, which copies one value over the whole block. Shift from the right end down.
    • Assuming this is still O(n log n). The shifting makes the worst case quadratic.

    Similar problems