Merge Two Sorted Arrays in C++
Merge two sorted arrays into one sorted array in C++ with indexes i, j, and k. Covers the two-pointer comparison, leftover copy loops, and O(n1 + n2) cost.
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}
Sample Output
Merged array: 1 2 3 4 5 6 7 8
Sorted result.
In this one
- How two pointers walk two sorted arrays at once
- Why the smaller front element goes next
- Why leftover elements must be copied after the main loop
- How this step powers merge sort
How it works
- 1
i, j, k start at 0.
- 2
Compare arr1[i] and arr2[j]; copy the smaller to merged[k].
- 3
Advance the index you copied from, and k.
- 4
When one array runs out, copy the rest of the other.
- 5
Print 1 2 3 4 5 6 7 8.
First four steps
Which element is taken.
- 1.1 < 2 → take 1
- 2.3 > 2 → take 2
- 3.3 < 4 → take 3
- 4.5 > 4 → take 4
Edge cases
Unequal lengths
Use {1, 2} and {3, 4, 5, 6}.
The main loop ends after arr1 runs out, and the second leftover loop copies 3 4 5 6.
Equal values
Use {1, 3} and {1, 2}.
arr1[i] < arr2[j] is false for 1 vs 1, so the element from arr2 goes first. Using <= would take arr1 first and keep the merge stable.
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
#include <algorithm>
int merged[n1 + n2];
merge(arr1, arr1 + n1, arr2, arr2 + n2, merged);
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;
// Add all elements, then extract
// Less efficient but demonstrates priority queue usage
Method 5: Using Recursion
vector<int> mergeRecursive(vector<int>& arr1, vector<int>& arr2) {
// Recursive merge implementation
// Base case: one array empty
// Recursive case: compare and merge
}
Displaying the Result
The program prints:
cout << "Merged array: ";
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.
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
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.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is the time complexity?
Pick an answer to check it.
Question 2
After the main loop, can both leftover loops copy elements?
Pick an answer to check it.
Questions people ask
Does this work on unsorted input?
No. The output is only sorted if both inputs are sorted.
Is there a library function?
std::merge in <algorithm> does exactly this.
Why are there two leftover loops?
You do not know which array runs out first; only one of them will actually run.