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

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


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 Posts:



    Article Tags :
    Practice Tags :


    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.