Given two sorted arrays, the task is to merge them into a single array while maintaining the sorted order.
- The merged array contains all elements from both arrays, including duplicates.
- The optimal approach uses two pointers to merge the arrays in O(n1 + n2) time.
Examples:Â
Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8}Â
Output: arr3[] = {4, 5, 7, 8, 8, 9}Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8}Â
Output: arr3[] = {4, 5, 7, 8, 8, 9}
Approaches to Merge Two Sorted Arrays
The problem can be solved using the following approaches:
Naive Approach
The simplest approach is to copy all elements from both arrays into a third array and then sort the resulting array.
Steps:
- Create a result array of size n1 + n2.
- Copy all elements of the first array into it.
- Copy all elements of the second array into it.
- Sort the result array.
- Return or print the merged array.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Function to merge two sorted arrays
vector<int> mergeArrays(const vector<int>& arr1,
const vector<int>& arr2)
{
vector<int> arr3;
arr3.insert(arr3.end(), arr1.begin(), arr1.end());
arr3.insert(arr3.end(), arr2.begin(), arr2.end());
sort(arr3.begin(), arr3.end());
return arr3;
}
int main()
{
vector<int> arr1 = {1, 3, 5, 7};
vector<int> arr2 = {2, 4, 6, 8};
vector<int> result = mergeArrays(arr1, arr2);
cout << "Merged array: ";
for (int x : result)
cout << x << " ";
return 0;
}
Output
Merged array: 1 2 3 4 5 6 7 8
Explanation: The elements of both sorted arrays are first copied into arr3. Since their combined order is not guaranteed, sort() is then used to arrange all elements in ascending order.
Insertion-Based Approach
In this approach, all elements of the first array are copied into the result array. Then, each element of the second array is inserted into its correct position, similar to the insertion sort technique.
Steps:
- Create a result array containing all elements of arr1.
- Traverse arr2 one element at a time.
- Find the correct position for the current element in the result array.
- Shift larger elements one position to the right.
- Insert the current element at its correct position.
- Repeat until all elements of arr2 are inserted.
#include <iostream>
#include <vector>
using namespace std;
// Function to merge two sorted arrays
vector<int> mergeArrays(const vector<int>& arr1,
const vector<int>& arr2)
{
vector<int> result = arr1;
// Process each element of arr2
for (int x : arr2) {
int pos = result.size();
// Find the position where x should be inserted
while (pos > 0 && result[pos - 1] > x) {
--pos;
}
// Insert x at the correct position
result.insert(result.begin() + pos, x);
}
return result;
}
int main()
{
vector<int> arr1 = {1, 3, 5, 7};
vector<int> arr2 = {2, 4, 6, 8};
vector<int> result = mergeArrays(arr1, arr2);
cout << "Merged array: ";
for (int x : result)
cout << x << " ";
return 0;
}
Output
Merged array: 1 2 3 4 5 6 7 8
Explanation: The result array initially contains all elements of arr1. Each element of arr2 is then inserted into its appropriate position. Before insertion, elements greater than the current value are shifted one position to the right.
Two-Pointer Approach
Since both arrays are already sorted, we can merge them directly without sorting or repeatedly shifting elements. Two pointers, i and j, are used to track the current elements of arr1 and arr2.
Steps:
- Initialize i and j to 0.
- Compare arr1[i] and arr2[j].
- Add the smaller element to the result and move its pointer forward.
- Continue until one array is completely traversed.
- Copy the remaining elements of the other array into the result.
Dry Run
The following dry run illustrates how the two pointers merge the arrays step by step.

For example, for:
arr1 = {5, 8, 9}
arr2 = {4, 7, 8}
the elements are processed as follows:
4 < 5 -> 4
5 < 7 -> 5
7 < 8 -> 7
8 <= 8 -> 8
8 < 9 -> 8
remaining -> 9
The final merged array is:
{4, 5, 7, 8, 8, 9}
Implementation
#include <iostream>
#include <vector>
using namespace std;
// Function to merge two sorted arrays
vector<int> mergeArrays(const vector<int>& arr1,
const vector<int>& arr2)
{
vector<int> result;
int i = 0, j = 0;
// Compare elements from both arrays
while (i < arr1.size() && j < arr2.size()) {
if (arr1[i] <= arr2[j])
result.push_back(arr1[i++]);
else
result.push_back(arr2[j++]);
}
// Add remaining elements of arr1
while (i < arr1.size())
result.push_back(arr1[i++]);
// Add remaining elements of arr2
while (j < arr2.size())
result.push_back(arr2[j++]);
return result;
}
int main()
{
vector<int> arr1 = {1, 3, 5, 7};
vector<int> arr2 = {2, 4, 6, 8};
vector<int> result = mergeArrays(arr1, arr2);
cout << "Merged array: ";
for (int x : result)
cout << x << " ";
return 0;
}
Output
Merged array: 1 2 3 4 5 6 7 8
Explanation
- The pointers always point to the smallest unprocessed elements of their respective arrays. The smaller element is added to the result, and the corresponding pointer is advanced.
- When one array is completely traversed, the remaining elements of the other array are already sorted, so they can be copied directly to the result.
Map-Based Approach
A map can also be used to merge the arrays while maintaining their elements in sorted order.
Steps:
- Create a map to store each element and its frequency.
- Insert all elements of the first array into the map.
- Insert all elements of the second array into the map.
- Traverse the map in sorted key order.
- Print each key according to its stored frequency.
#include <iostream>
#include <map>
#include <vector>
using namespace std;
// Function to merge two arrays using a map
vector<int> mergeArrays(const vector<int>& arr1,
const vector<int>& arr2)
{
map<int, int> freq;
// Store frequencies of both arrays
for (int x : arr1)
freq[x]++;
for (int x : arr2)
freq[x]++;
vector<int> result;
// Map stores keys in sorted order
for (auto& [value, count] : freq) {
while (count--)
result.push_back(value);
}
return result;
}
int main()
{
vector<int> arr1 = {1, 3, 5, 7};
vector<int> arr2 = {2, 4, 6, 8};
vector<int> result = mergeArrays(arr1, arr2);
cout << "Merged array: ";
for (int x : result)
cout << x << " ";
return 0;
}
Output
Merged array: 1 2 3 4 5 6 7 8
Explanation: The map stores each distinct element as a key and its total frequency as the corresponding value. Since std::map keeps keys sorted, traversing the map produces the merged elements in sorted order. Repeating each key according to its frequency also preserves duplicate elements.