In-Place Merge Sort | Set 2
Given an array A[] of size N, the task is to sort the array in increasing order using In-Place Merge Sort.
Examples:
Input: A = {5, 6, 3, 2, 1, 6, 7}
Output: {1, 2, 3, 5, 6, 6, 7}Input: A = {2, 3, 4, 1}
Output: {1, 2, 3, 4}
Approach: The idea is to use the inplace_merge() function to merge the sorted arrays in O(1) space. Follow the steps below to solve the problem:
- Create a recursive function mergeSort() that accepts the start and the end indices of the array as parameters. Now, perform the following steps:
- If size of the array is equal to 1, simply return out of the function.
- Otherwise, calculate the middle index to split the array into two subarrays.
- Recursively call mergeSort() on the left and right subarrays to sort them separately.
- Then, call the inplace_merge() function to merge the two subarrays.
- After completing the above steps, print the sorted array A[].
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> #define it vector<int>::iterator using namespace std; // Recursive function to split the array // into two subarrays and sort them void mergeSortUtil(it left, it right) { // Handle the base case if (right - left <= 1) return ; // Otherwise, find the middle index it mid = left + (right - left) / 2; // Recursively sort // the left subarray mergeSortUtil(left, mid); // Recursively sort // the right subarray mergeSortUtil(mid, right); // Merge the two sorted arrays using // inplace_merge() function inplace_merge(left, mid, right); return ; } // Function to sort the array // using inplace Merge Sort void mergeSort(vector< int > arr) { // Recursive function to sort the array mergeSortUtil(arr.begin(), arr.end()); // Print the sorted array for ( int el : arr) cout << el << " " ; } // Driver Code int main() { vector< int > arr = { 5, 6, 3, 2, 1, 6, 7 }; mergeSort(arr); return 0; } |
1 2 3 5 6 6 7
Time Complexity: O(N * log(N))
Auxiliary Space: O(1)
Alternate Approaches: Refer to the previous article for other approaches to solve this problem.