C++ Program to Merge 3 Sorted Arrays
Last Updated :
18 Aug, 2023
Given 3 arrays (A, B, C) which are sorted in ascending order, we are required to merge them together in ascending order and output the array D.
Examples:
Input : A = [1, 2, 3, 4, 5]
B = [2, 3, 4]
C = [4, 5, 6, 7]
Output : D = [1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 7]
Input : A = [1, 2, 3, 5]
B = [6, 7, 8, 9 ]
C = [10, 11, 12]
Output: D = [1, 2, 3, 5, 6, 7, 8, 9. 10, 11, 12]
Method 1 (Two Arrays at a time)
We have discussed at Merging 2 Sorted arrays . So we can first merge two arrays and then merge the resultant with the third array. Time Complexity for merging two arrays O(m+n). So for merging the third array, the time complexity will become O(m+n+o). Note that this is indeed the best time complexity that can be achieved for this problem.
Space Complexity: Since we merge two arrays at a time, we need another array to store the result of the first merge. This raises the space complexity to O(m+n). Note that space required to hold the result of 3 arrays is ignored while calculating complexity.
Algorithm
function merge(A, B)
Let m and n be the sizes of A and B
Let D be the array to store result
// Merge by taking smaller element from A and B
while i < m and j < n
if A[i] <= B[j]
Add A[i] to D and increment i by 1
else Add B[j] to D and increment j by 1
// If array A has exhausted, put elements from B
while j < n
Add B[j] to D and increment j by 1
// If array B has exhausted, put elements from A
while i < n
Add A[j] to D and increment i by 1
Return D
function merge_three(A, B, C)
T = merge(A, B)
return merge(T, C)
The Implementations are given below
C++
// C++ program to merge three sorted arrays
// by merging two at a time.
#include <iostream>
#include <vector>
using namespace std;
using Vector = vector<int>;
void printVector(const Vector& a)
{
cout << "[";
for (auto e : a)
cout << e << " ";
cout << "]" << endl;
}
Vector mergeTwo(Vector& A, Vector& B)
{
// Get sizes of vectors
int m = A.size();
int n = B.size();
// Vector for storing Result
Vector D;
D.reserve(m + n);
int i = 0, j = 0;
while (i < m && j < n) {
if (A[i] <= B[j])
D.push_back(A[i++]);
else
D.push_back(B[j++]);
}
// B has exhausted
while (i < m)
D.push_back(A[i++]);
// A has exhausted
while (j < n)
D.push_back(B[j++]);
return D;
}
// Driver Code
int main()
{
Vector A = { 1, 2, 3, 5 };
Vector B = { 6, 7, 8, 9 };
Vector C = { 10, 11, 12 };
// First Merge A and B
Vector T = mergeTwo(A, B);
// Print Result after merging T with C
printVector(mergeTwo(T, C));
return 0;
}
Output:
[1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12]
Method 2 (Three arrays at a time)
The Space complexity of method 1 can be improved we merge the three arrays together.
function merge-three(A, B, C)
Let m, n, o be size of A, B, and C
Let D be the array to store the result
// Merge three arrays at the same time
while i < m and j < n and k < o
Get minimum of A[i], B[j], C[i]
if the minimum is from A, add it to
D and advance i
else if the minimum is from B add it
to D and advance j
else if the minimum is from C add it
to D and advance k
// After above step at least 1 array has
// exhausted. Only C has exhausted
while i < m and j < n
put minimum of A[i] and B[j] into D
Advance i if minimum is from A else advance j
// Only B has exhausted
while i < m and k < o
Put minimum of A[i] and C[k] into D
Advance i if minimum is from A else advance k
// Only A has exhausted
while j < n and k < o
Put minimum of B[j] and C[k] into D
Advance j if minimum is from B else advance k
// After above steps at least 2 arrays have
// exhausted
if A and B have exhausted take elements from C
if B and C have exhausted take elements from A
if A and C have exhausted take elements from B
return D
Complexity: The Time Complexity is O(m+n+o) since we process each element from the three arrays once. We only need one array to store the result of merging and so ignoring this array, the space complexity is O(1).
Implementation of the algorithm is given below:
C++
// C++ program to merger three sorted arrays
// by merging three simultaneously.
#include <iostream>
#include <vector>
using namespace std;
using Vector = vector<int>;
void printVector(const Vector& a)
{
cout << "[";
for (auto e : a) {
cout << e << " ";
}
cout << "]" << endl;
}
Vector mergeThree(Vector& A, Vector& B,
Vector& C)
{
int m, n, o, i, j, k;
// Get Sizes of three vectors
m = A.size();
n = B.size();
o = C.size();
// Vector for storing output
Vector D;
D.reserve(m + n + o);
i = j = k = 0;
while (i < m && j < n && k < o) {
// Get minimum of a, b, c
int m = min(min(A[i], B[j]), C[k]);
// Put m in D
D.push_back(m);
// Increment i, j, k
if (m == A[i])
i++;
else if (m == B[j])
j++;
else
k++;
}
// C has exhausted
while (i < m && j < n) {
if (A[i] <= B[j]) {
D.push_back(A[i]);
i++;
}
else {
D.push_back(B[j]);
j++;
}
}
// B has exhausted
while (i < m && k < o) {
if (A[i] <= C[k]) {
D.push_back(A[i]);
i++;
}
else {
D.push_back(C[k]);
k++;
}
}
// A has exhausted
while (j < n && k < o) {
if (B[j] <= C[k]) {
D.push_back(B[j]);
j++;
}
else {
D.push_back(C[k]);
k++;
}
}
// A and B have exhausted
while (k < o)
D.push_back(C[k++]);
// B and C have exhausted
while (i < m)
D.push_back(A[i++]);
// A and C have exhausted
while (j < n)
D.push_back(B[j++]);
return D;
}
// Driver Code
int main()
{
Vector A = { 1, 2, 41, 52, 84 };
Vector B = { 1, 2, 41, 52, 67 };
Vector C = { 1, 2, 41, 52, 67, 85 };
// Print Result
printVector(mergeThree(A, B, C));
return 0;
}
Output[1 1 1 2 2 2 41 41 41 52 52 52 67 67 84 85 ]
Note: While it is relatively easy to implement direct procedures to merge two or three arrays, the process becomes cumbersome if we want to merge 4 or more arrays. In such cases, we should follow the procedure shown in Merge K Sorted Arrays .
Another Approach (Without caring about the exhausting array):
The code written above can be shortened by the below code. Here we do not need to write code if any array gets exhausted.
Below is the implementation of the above approach:
C++
// C++ program to merge three sorted arrays
// Without caring about the exhausting array
#include <bits/stdc++.h>
using namespace std;
// A[], B[], C[]: input arrays
// Function to merge three sorted lists into a single
// list.
vector<int> merge3sorted(vector<int>& A, vector<int>& B,
vector<int>& C)
{
vector<int> ans;
int l1 = A.size();
int l2 = B.size();
int l3 = C.size();
int i = 0, j = 0, k = 0;
while (i < l1 || j < l2 || k < l3) {
// Assigning a, b, c with max values so that if
// any value is not present then also we can sort
// the array.
int a = INT_MAX, b = INT_MAX, c = INT_MAX;
// a, b, c variables are assigned only if the
// value exist in the array.
if (i < l1)
a = A[i];
if (j < l2)
b = B[j];
if (k < l3)
c = C[k];
// Checking if 'a' is the minimum
if (a <= b && a <= c) {
ans.push_back(a);
i++;
}
// Checking if 'b' is the minimum
else if (b <= a && b <= c) {
ans.push_back(b);
j++;
}
// Checking if 'c' is the minimum
else {
if (c <= a && c <= b) {
ans.push_back(c);
k++;
}
}
}
return ans;
}
// A utility function to print array list
void printeSorted(vector<int> list)
{
for (auto x : list)
cout << x << " ";
}
// Driver program to test above functions
int main()
{
vector<int> A = { 1, 2, 41, 52, 84 };
vector<int> B = { 1, 2, 41, 52, 67 };
vector<int> C = { 1, 2, 41, 52, 67, 85 };
vector<int> final_ans = merge3sorted(A, B, C);
printeSorted(final_ans);
return 0;
}
// This code is contributed by Pushpesh raj
Output1 1 1 2 2 2 41 41 41 52 52 52 67 67 84 85
Time Complexity: O(m+n+o) where m, n, o are the lengths of the 1st, 2nd, and 3rd arrays.
Space Complexity: O(m+n+o) where m, n, o are the lengths of the 1st, 2nd, and 3rd arrays. Space used for the output array.
Please refer complete article on Merge 3 Sorted Arrays for more details!
Similar Reads
C++ Program to Merge Two Sorted Arrays
Given two sorted arrays, the task is to merge them in a sorted manner.Examples:Â Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8}Â Output: arr3[] = {1, 2, 3, 4, 4, 5, 6, 8} Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8}Â Output: arr3[] = {4, 5, 7, 8, 8, 9}Â Recommended: Please solve it on âPRACTIC
5 min read
C++ Program For Merge Sort
Merge Sort is a comparison-based sorting algorithm that uses divide and conquer paradigm to sort the given dataset. It divides the dataset into two halves, calls itself for these two halves, and then it merges the two sorted halves.In this article, we will learn how to implement merge sort in a C++
4 min read
C++ Program To Merge Two Sorted Lists (In-Place)
Write a C++ program to merge two sorted linked lists into a single sorted linked list in place (i.e. without using extra space).Examples:Input: List1: 5 -> 7 -> 9, list2: 4 -> 6 -> 8 Output: 4->5->6->7->8->9Input: List1: 1 -> 3 -> 5 -> 7, List2: 2 -> 4Output: 1
3 min read
C++ Program to Find the Second Largest Element in an Array
In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we will learn how to find the second largest element in an array in C++. Examples: Input: arr[] = {34, 5, 16, 14, 56, 7, 56} Output: 34 Explanation: The
3 min read
C++ Program To Merge K Sorted Linked Lists - Set 1
Given K sorted linked lists of size N each, merge them and print the sorted output. Examples: Input: k = 3, n = 4 list1 = 1->3->5->7->NULL list2 = 2->4->6->8->NULL list3 = 0->9->10->11->NULL Output: 0->1->2->3->4->5->6->7->8->9->10-
6 min read
Array C/C++ Programs
C Program to find sum of elements in a given arrayC program to find largest element in an arrayC program to multiply two matricesC/C++ Program for Given an array A[] and a number x, check for pair in A[] with sum as xC/C++ Program for Majority ElementC/C++ Program for Find the Number Occurring Odd N
6 min read
C++ Program to Sort the Elements of an Array in Ascending Order
Here, we will see how to sort the elements of an array in ascending order using a C++ program. Below are the examples: Input: 3 4 5 8 1 10Output: 1 3 4 5 8 10 Input: 11 34 6 20 40 3Output: 3 6 11 20 34 40 There are 2 ways to sort an array in ascending order in C++: Brute-force Approach Using Bubble
4 min read
C++ Program For Row Wise Sorting in 2D Array
Given a 2D array, sort each row of this array and print the result.Examples: Input: 77 11 22 3 11 89 1 12 32 11 56 7 11 22 44 33 Output: 3 11 22 77 1 11 12 89 7 11 32 56 11 22 33 44 Input: 8 6 4 5 3 5 2 1 9 7 4 2 7 8 9 5 Output: 4 5 6 8 1 2 3 5 2 4 7 9 5 7 8 9 Method 1 (Using Bubble Sort): Start ite
3 min read
C++ Program to Find Largest Element in an Array
In this article, we will learn to write a C++ program to find the largest element in the given array arr of size N. The element that is greater than all other elements is the largest element in the array. Recommended PracticeHelp a Thief!!!Try It! One of the most simplest and basic approaches to fin
2 min read
C++ Program to Print all triplets in sorted array that form AP
Given a sorted array of distinct positive integers, print all triplets that form AP (or Arithmetic Progression)Examples :Â Â Input : arr[] = { 2, 6, 9, 12, 17, 22, 31, 32, 35, 42 }; Output : 6 9 12 2 12 22 12 17 22 2 17 32 12 22 32 9 22 35 2 22 42 22 32 42 Input : arr[] = { 3, 5, 6, 7, 8, 10, 12}; Ou
4 min read