Given two sorted arrays, arr[], brr[] of size N, and M, the task is to merge the two given arrays such that they form a sorted sequence of integers combining elements of both the arrays.
Examples:
Input: arr[] = {10}, brr[] = {2, 3}
Output: 2 3 10
Explanation: The merged sorted array obtained by taking all the elements from the both the arrays is {2, 3, 10}.Â
Therefore, the required output is 2 3 10.Input: arr[] = {1, 5, 9, 10, 15, 20}, brr[] = {2, 3, 8, 13}
Output: 1 2 3 5 8 9 10 13 15 20
Naive Approach: Refer to Merge two sorted arrays for the simplest approach to merge the two given arrays.
Time Complexity: O(N * M)
Auxiliary Space: O(1)
Space Optimized Approach: Refer to Merge two sorted arrays with O(1) extra space to merge the two given arrays without using any extra memory.
Time Complexity: O(N * M)
Auxiliary Space: O(1)
Efficient Space Optimized Approach: Refer to Efficiently merging two sorted arrays with O(1) extra space to merge the two given array without using any extra memory.
Time Complexity: O((N + M) * log(N + M))
Auxiliary Space: O(1)
Heap – based Approach: The problem can be solved using Heap. The idea is to traverse arr[] array and compare the value of arr[i] with brr[0] and check if arr[i] is greater than brr[0] or not. If found to be true then swap(arr[i], brr[0) and perform the heapify operation on brr[]. Follow the steps below to solve the problem:
- Traverse the array arr[] and compare the value of arr[i] with brr[0] and check if arr[i] is greater than brr[0] or not. If found to be true then swap(arr[i], brr[0) and perform the heapify operation on brr[].
- Finally, sort the array brr[] and print both arrays.
Below is the implementation of the above approach:
C++
// C++ program to implement // the above approach Â
#include <bits/stdc++.h> using namespace std; Â
// Function to perform min heapify // on array brr[] void minHeapify( int brr[], int i, int M) { Â
    // Stores index of left child     // of i.     int left = 2 * i + 1; Â
    // Stores index of right child     // of i.     int right = 2 * i + 2; Â
    // Stores index of the smallest element     // in (arr[i], arr[left], arr[right])     int smallest = i; Â
    // Check if arr[left] less than     // arr[smallest]     if (left < M && brr[left] < brr[smallest]) { Â
        // Update smallest         smallest = left;     } Â
    // Check if arr[right] less than     // arr[smallest]     if (right < M && brr[right] < brr[smallest]) { Â
        // Update smallest         smallest = right;     } Â
    // if i is not the index     // of smallest element     if (smallest != i) { Â
        // Swap arr[i] and arr[smallest]         swap(brr[i], brr[smallest]); Â
        // Perform heapify on smallest         minHeapify(brr, smallest, M);     } } Â
// Function to merge two sorted arrays void merge( int arr[], int brr[], Â Â Â Â Â Â Â Â Â Â Â int N, int M) { Â
    // Traverse the array arr[]     for ( int i = 0; i < N; ++i) { Â
        // Check if current element         // is less than brr[0]         if (arr[i] > brr[0]) { Â
            // Swap arr[i] and brr[0]             swap(arr[i], brr[0]); Â
            // Perform heapify on brr[]             minHeapify(brr, 0, M);         }     } Â
    // Sort array brr[]     sort(brr, brr + M); } Â
// Function to print array elements void printArray( int arr[], int N) { Â
    // Traverse array arr[]     for ( int i = 0; i < N; i++)         cout << arr[i] << " " ; } Â
// Driver Code int main() { Â Â Â Â int arr[] = { 2, 23, 35, 235, 2335 }; Â Â Â Â int brr[] = { 3, 5 }; Â Â Â Â int N = sizeof (arr) / sizeof (arr[0]); Â Â Â Â int M = sizeof (brr) / sizeof (brr[0]); Â
    // Function call to merge     // two array     merge(arr, brr, N, M); Â
    // Print first array     printArray(arr, N); Â
    // Print Second array.     printArray(brr, M); Â
    return 0; } |
Java
// Java program to implement // the above approach import java.util.*; class GFG{ Â
// Function to perform // min heapify on array // brr[] static void minHeapify( int brr[],                        int i, int M) {   // Stores index of left   // child of i.   int left = 2 * i + 1 ; Â
  // Stores index of right   // child of i.   int right = 2 * i + 2 ; Â
  // Stores index of the smallest   // element in (arr[i], arr[left],   // arr[right])   int smallest = i; Â
  // Check if arr[left] less than   // arr[smallest]   if (left < M && brr[left] <       brr[smallest])   {     // Update smallest     smallest = left;   } Â
  // Check if arr[right] less   // than arr[smallest]   if (right < M && brr[right] <       brr[smallest])   {     // Update smallest     smallest = right;   } Â
  // if i is not the index   // of smallest element   if (smallest != i)   {     // Swap arr[i] and     // arr[smallest]     int temp = brr[i];     brr[i] = brr[smallest];     brr[smallest] = temp; Â
    // Perform heapify on smallest     minHeapify(brr, smallest, M);   } } Â
// Function to merge two // sorted arrays static void merge( int arr[], int brr[],                   int N, int M) {   // Traverse the array arr[]   for ( int i = 0 ; i < N; ++i)   {     // Check if current element     // is less than brr[0]     if (arr[i] > brr[ 0 ])     {       // Swap arr[i] and brr[0]       int temp = arr[i];       arr[i] = brr[ 0 ];       brr[ 0 ] = temp; Â
      // Perform heapify on brr[]       minHeapify(brr, 0 , M);     }   } Â
  // Sort array brr[]   Arrays.sort(brr); } Â
// Function to print array // elements static void printArray( int arr[], Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int N) { Â Â // Traverse array arr[] Â Â for ( int i = 0 ; i < N; i++) Â Â Â Â System.out.print(arr[i] + " " ); } Â
// Driver Code public static void main(String[] args) { Â Â int arr[] = { 2 , 23 , 35 , 235 , 2335 }; Â Â int brr[] = { 3 , 5 }; Â Â int N = arr.length; Â Â int M = brr.length; Â
  // Function call to merge   // two array   merge(arr, brr, N, M); Â
  // Print first array   printArray(arr, N); Â
  // Print Second array.   printArray(brr, M); } } Â
// This code is contributed by Rajput-Ji |
Python3
# Python3 program to implement # the above approach Â
# Function to perform min heapify # on array brr[] def minHeapify(brr, i, M): Â
    # Stores index of left child     # of i.     left = 2 * i + 1 Â
    # Stores index of right child     # of i.     right = 2 * i + 2 Â
    # Stores index of the smallest element     # in (arr[i], arr[left], arr[right])     smallest = i Â
    # Check if arr[left] less than     # arr[smallest]     if (left < M and brr[left] < brr[smallest]): Â
        # Update smallest         smallest = left Â
    # Check if arr[right] less than     # arr[smallest]     if (right < M and brr[right] < brr[smallest]): Â
        # Update smallest         smallest = right Â
    # If i is not the index     # of smallest element     if (smallest ! = i): Â
        # Swap arr[i] and arr[smallest]         brr[i], brr[smallest] = brr[smallest], brr[i] Â
        # Perform heapify on smallest         minHeapify(brr, smallest, M) Â
# Function to merge two sorted arrays def merge(arr, brr, N, M): Â
    # Traverse the array arr[]     for i in range (N): Â
        # Check if current element         # is less than brr[0]         if (arr[i] > brr[ 0 ]): Â
            # Swap arr[i] and brr[0]             arr[i], brr[ 0 ] = brr[ 0 ], arr[i] Â
            # Perform heapify on brr[]             minHeapify(brr, 0 , M) Â
    # Sort array brr[]     brr.sort() Â
# Function to print array elements def printArray(arr, N): Â
    # Traverse array arr[]     for i in range (N):         print (arr[i], end = " " ) Â
# Driver code if __name__ = = '__main__' : Â
    arr = [ 2 , 23 , 35 , 235 , 2335 ]     brr = [ 3 , 5 ]     N = len (arr)     M = len (brr) Â
    # Function call to merge     # two array     merge(arr, brr, N, M) Â
    # Print first array     printArray(arr, N) Â
    # Print Second array.     printArray(brr, M) Â
# This code is contributed by Shivam Singh |
C#
// C# program to implement // the above approach using System; Â
class GFG{ Â
// Function to perform // min heapify on array // brr[] static void minHeapify( int []brr,                        int i, int M) {      // Stores index of left   // child of i.   int left = 2 * i + 1; Â
  // Stores index of right   // child of i.   int right = 2 * i + 2; Â
  // Stores index of the smallest   // element in (arr[i], arr[left],   // arr[right])   int smallest = i; Â
  // Check if arr[left] less than   // arr[smallest]   if (left < M && brr[left] <       brr[smallest])   {          // Update smallest     smallest = left;   } Â
  // Check if arr[right] less   // than arr[smallest]   if (right < M && brr[right] <       brr[smallest])   {          // Update smallest     smallest = right;   } Â
  // If i is not the index   // of smallest element   if (smallest != i)   {          // Swap arr[i] and     // arr[smallest]     int temp = brr[i];     brr[i] = brr[smallest];     brr[smallest] = temp; Â
    // Perform heapify on smallest     minHeapify(brr, smallest, M);   } } Â
// Function to merge two // sorted arrays static void merge( int []arr, int []brr,                   int N, int M) {      // Traverse the array []arr   for ( int i = 0; i < N; ++i)   {          // Check if current element     // is less than brr[0]     if (arr[i] > brr[0])     {              // Swap arr[i] and brr[0]       int temp = arr[i];       arr[i] = brr[0];       brr[0] = temp; Â
      // Perform heapify on brr[]       minHeapify(brr, 0, M);     }   } Â
  // Sort array brr[]   Array.Sort(brr); } Â
// Function to print array // elements static void printArray( int []arr,                        int N) {      // Traverse array []arr   for ( int i = 0; i < N; i++)     Console.Write(arr[i] + " " ); } Â
// Driver Code public static void Main(String[] args) { Â Â int []arr = { 2, 23, 35, 235, 2335 }; Â Â int []brr = {3, 5}; Â Â int N = arr.Length; Â Â int M = brr.Length; Â
  // Function call to merge   // two array   merge(arr, brr, N, M); Â
  // Print first array   printArray(arr, N); Â
  // Print Second array.   printArray(brr, M); } } Â
// This code is contributed by Amit Katiyar |
Javascript
<script> Â
// Javascript program to implement // the above approach Â
// Function to perform min heapify // on array brr[] function minHeapify(brr, i, M) { Â
    // Stores index of left child     // of i.     let left = 2 * i + 1; Â
    // Stores index of right child     // of i.     let right = 2 * i + 2; Â
    // Stores index of the smallest element     // in (arr[i], arr[left], arr[right])     let smallest = i; Â
    // Check if arr[left] less than     // arr[smallest]     if (left < M && brr[left] < brr[smallest]) { Â
        // Update smallest         smallest = left;     } Â
    // Check if arr[right] less than     // arr[smallest]     if (right < M && brr[right] < brr[smallest]) { Â
        // Update smallest         smallest = right;     } Â
    // if i is not the index     // of smallest element     if (smallest != i) { Â
        // Swap arr[i] and arr[smallest]         let temp = brr[i];         brr[i] = brr[smallest];         brr[smallest] = temp;   Â
        // Perform heapify on smallest         minHeapify(brr, smallest, M);     } } Â
// Function to merge two sorted arrays function merge(arr, brr, Â Â Â Â Â Â Â Â N, M) { Â
    // Traverse the array arr[]     for (let i = 0; i < N; ++i) { Â
        // Check if current element         // is less than brr[0]         if (arr[i] > brr[0]) { Â
            // Swap arr[i] and brr[0]             let temp = arr[i];               arr[i] = brr[0];               brr[0] = temp;   Â
            // Perform heapify on brr[]             minHeapify(brr, 0, M);         }     } Â
    // Sort array brr[]     brr.sort(); } Â
// Function to print array elements function printArray(arr, N) { Â
    // Traverse array arr[]     for (let i = 0; i < N; i++)         document.write(arr[i] + " " ); } Â
// Driver Code Â
    let arr = [ 2, 23, 35, 235, 2335 ];     let brr = [ 3, 5 ];     let N = arr.length;     let M = brr.length; Â
    // Function call to merge     // two array     merge(arr, brr, N, M); Â
    // Print first array     printArray(arr, N); Â
    // Print Second array.     printArray(brr, M); Â
Â
//This code is contributed by Mayank Tyagi </script> |
2 3 5 23 35 235 2335
Â
Time Complexity: O((N + M) * log (M))
Auxiliary Space: O(1)
Efficient Approach: Refer to merge two sorted arrays to efficiently merge the two given arrays.
Time Complexity: O(N + M)
Auxiliary Space: O(N + M)Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!