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

• Difficulty Level : Medium
• Last Updated : 13 Jun, 2022

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 ``#include ``using` `namespace` `std;`` ` `// Driver code``int` `main()``{``    ``int` `A[] = {1, 1, 9};``    ``int` `n = ``sizeof``(A)/``sizeof``(A);`` ` `    ``int` `B[] = {2, 7, 11, 11};``    ``int` `m  = ``sizeof``(B)/``sizeof``(B);`` ` `    ``// 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