Merge Two Sorted Arrays
Merge Two Sorted Arrays in C++ (5 Examples)
IntermediateTopic: Array Operations Programs
C++ Merge Two Sorted Arrays Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arr1[] = {1, 3, 5, 7};
int arr2[] = {2, 4, 6, 8};
int n1 = 4, n2 = 4;
int merged[n1 + n2];
int i = 0, j = 0, k = 0;
// Merge while both arrays have elements
while (i < n1 && j < n2) {
if (arr1[i] < arr2[j]) {
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}
// Copy remaining elements
while (i < n1) merged[k++] = arr1[i++];
while (j < n2) merged[k++] = arr2[j++];
cout << "Merged array: ";
for (int i = 0; i < n1 + n2; i++) {
cout << merged[i] << " ";
}
cout << endl;
return 0;
}Output
Merged array: 1 2 3 4 5 6 7 8
Understanding Merge Two Sorted Arrays
This program demonstrates 5 different methods to merge two sorted arrays: using two pointers, using merge() algorithm, using vectors, using priority queue, and using recursion.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.