Skip to content
Related Articles

Related Articles

Quickly merging two sorted arrays using std::merge() in C++ STL

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 13 Jun, 2022
View Discussion
Improve Article
Save Article

C++ program to merge two sorted arrays of length ‘n’ and ‘m’ respectively in sorted order.

Examples:

Input: A[] = {3, 6, 9}
       B[] = {2, 7, 11}
Output: C[] = {2, 3, 6, 7, 9, 11}

Input: A[] = {1, 1, 3, 6, 9}
       B[] = {1, 2, 7, 11, 11}
Output: C[] = {1, 1, 1, 2, 3, 6, 7, 9, 11, 11}

We have discussed other approaches in below posts
Merge two sorted arrays with O(1) extra space
Merge two sorted arrays

We can quickly merge two sorted arrays using std::merge present algorithm header file.

Below is the implementation using std :: merge




// C++ program to merge two sorted arrays
// std::merge()
#include <iostream>
#include <algorithm>
using namespace std;
  
// Driver code
int main()
{
    int A[] = {1, 1, 9};
    int n = sizeof(A)/sizeof(A[0]);
  
    int B[] = {2, 7, 11, 11};
    int m  = sizeof(B)/sizeof(B[0]);
  
    // Merging in sorted order
    int C[m + n];
    merge(A, (A + n), B, (B + m), C);
  
    // Print the merged array.
    for (int i = 0; i < (m + n); i++)
        cout << C[i] << " ";
  
    return 0;
}

Output:

1 1 2 7 9 11 11 

In general, syntax of merge() is

// Merges elements from aFirst to aLast and bFirst
// to bLast into a result and returns iterator pointing
// to first element of result
OutputItr merge(InputItr1 aFirst, InputItr1 aLast,
                InputItr2 bFirst, InputItr2 bLast,
                OutputItr result);

We can use it for array of user defined objects
also by overloading < operator.

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!