Merge Two Sorted Arrays in C++
Merge Two Sorted Arrays in C++ (5 Examples).
1#include <iostream>2#include <algorithm>3using namespace std;45int main() {6 int arr1[] = {1, 3, 5, 7};7 int arr2[] = {2, 4, 6, 8};8 int n1 = 4, n2 = 4;910 int merged[n1 + n2];11 int i = 0, j = 0, k = 0;1213 // Merge while both arrays have elements14 while (i < n1 && j < n2) {15 if (arr1[i] < arr2[j]) {16 merged[k++] = arr1[i++];17 } else {18 merged[k++] = arr2[j++];19 }20 }2122 // Copy remaining elements23 while (i < n1) merged[k++] = arr1[i++];24 while (j < n2) merged[k++] = arr2[j++];2526 cout << "Merged array: ";27 for (int i = 0; i < n1 + n2; i++) {28 cout << merged[i] << " ";29 }30 cout << endl;3132 return 0;33}
Output
Merged array: 1 2 3 4 5 6 7 8
What's going on
The program takes two sorted arrays and merges them into one sorted array. For example:
The key is that both input arrays are already sorted, which allows efficient merging by comparing elements from both arrays.
Example:
Header Files Used
Declaring Variables
The program declares:
int arr1[] = {1, 3, 5, 7};
int arr2[] = {2, 4, 6, 8};
int n1 = 4, n2 = 4;
Creating the Merged Array
The program creates space for the merged result:
int merged[n1 + n2];
The Two-Pointer Merge Algorithm
The core algorithm uses two pointers (indices):
int i = 0, j = 0, k = 0;
Main Merge Loop
:
while (i < n1 && j < n2) {
if (arr1[i] < arr2[j]) {
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}
How it works step-by-step
(for [1,3,5,7] and [2,4,6,8]):
Initial: i=0, j=0, k=0
Step 1: i=1, j=0, k=1
Step 2: i=1, j=1, k=2
Step 3: i=2, j=1, k=3
Step 4: i=2, j=2, k=4
Step 5: i=3, j=2, k=5
Step 6: i=3, j=3, k=6
Loop ends (i >= n1), now copy remaining from arr2.
Copying Remaining Elements
After the main loop, one array may have remaining elements:
while (i < n1) merged[k++] = arr1[i++];
while (j < n2) merged[k++] = arr2[j++];
Why needed?
In our example:
Other Methods (Mentioned but not shown in code)
Method 2: Using merge() Algorithm
int merged[n1 + n2];
merge(arr1, arr1 + n1, arr2, arr2 + n2, merged);
1#include <algorithm>
Method 3: Using Vectors
vector<int> vec1(arr1, arr1 + n1);
vector<int> vec2(arr2, arr2 + n2);
vector<int> merged;
merge(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), back_inserter(merged));
Method 4: Using Priority Queue
priority_queue<int, vector<int>, greater<int>> pq;
1// Add all elements, then extract2// Less efficient but demonstrates priority queue usage
Method 5: Using Recursion
vector<int> mergeRecursive(vector<int>& arr1, vector<int>& arr2) {
}
1// Recursive merge implementation2// Base case: one array empty3// Recursive case: compare and merge
Displaying the Result
The program prints:
for (int i = 0; i < n1 + n2; i++) {
cout << merged[i] << " ";
}
Output:
Merged array: 1 2 3 4 5 6 7 8
The merged array contains all elements in sorted order.
1cout << "Merged array: ";
Understanding the Algorithm
Key Insight
: Since both arrays are sorted, we can merge efficiently by:
Why it works
:
Time and Space Complexity
Time Complexity
: O(n1 + n2)
Space Complexity
: O(n1 + n2)
When to Use Each Method
-
Two Pointers
: Best for learning - shows the algorithm clearly.
-
merge() Algorithm
: Best for most cases - simple, optimized, recommended.
-
Vectors
: When working with dynamic data or need vector features.
-
Priority Queue
: Less efficient - mainly for educational purposes.
-
Recursion
: Educational - helps understand recursive thinking.
Best Practice
: Use merge() for most applications - it's simple, efficient, and optimized.
Common Use Cases
Merge Sort
:
Combining Sorted Data
:
Interview Questions
:
Important Considerations
Both Arrays Must Be Sorted
:
Equal Elements
:
Different Array Sizes
:
return 0;
This ends the program successfully.