Quickly merging two sorted arrays using std::merge() in C++ STL
Last Updated :
14 Feb, 2023
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
CPP
#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]);
int C[m + n];
merge(A, (A + n), B, (B + m), C);
for ( int i = 0; i < (m + n); i++)
cout << C[i] << " ";
return 0;
}
|
Output:
1 1 2 7 9 11 11
Time Complexity: The time complexity of this algorithm is O(n + m), where n and m are the sizes of the two arrays.
Space Complexity: The space complexity of this algorithm is O(n + m), where n and m are the sizes of the two arrays. This is because we need to create a new array to store the merged elements, which takes O(n + m) space.
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.
Share your thoughts in the comments
Please Login to comment...