Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

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

  • Difficulty Level : Medium
  • Last Updated : 06 Jul, 2017

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

Examples:

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
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;
  
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 contribute.geeksforgeeks.org or mail your article to contribute@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 :