Given 3 arrays A[], B[], and C[] that are sorted in ascending order, the task is 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]
Naive Approach:
The naive approach to merge three sorted arrays would be to first concatenate all three arrays into a single array and then sort it in ascending order. This approach has a time complexity of O((n+m+p) log(n+m+p)), where n, m, and p are the lengths of the three arrays.
Algorithm:
- Take the size of the arrays A, B, and C as input from the user.
- Create arrays A, B, and C of the input size.
- Take the elements of arrays A, B, and C as input from the user.
- Merge arrays A, B, and C into a single array D.
- Sort array D in ascending order.
- Print the elements of array D.
Below is the implementation of the approach:
C++
// C++ code for the approach
#include <bits/stdc++.h>
using namespace std;
// Function to merge three sorted arrays
vector<int> mergeThreeSortedArrays(vector<int>& A, vector<int>& B, vector<int>& C) {
vector<int> D;
// Insert all elements from A into D
for (int i = 0; i < A.size(); i++) {
D.push_back(A[i]);
}
// Insert all elements from B into D
for (int i = 0; i < B.size(); i++) {
D.push_back(B[i]);
}
// Insert all elements from C into D
for (int i = 0; i < C.size(); i++) {
D.push_back(C[i]);
}
// Sort the merged array in ascending order
sort(D.begin(), D.end());
return D;
}
// Driver code
int main() {
vector<int> A = { 1, 2, 3, 5 };
vector<int> B = { 6, 7, 8, 9 };
vector<int> C = { 10, 11, 12 };
// Merge three sorted arrays
vector<int> D = mergeThreeSortedArrays(A, B, C);
// Print the merged and sorted array
for (int i = 0; i < D.size(); i++) {
cout << D[i] << " ";
}
cout << endl;
return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
// Function to merge three sorted arrays
static List<Integer>
mergeThreeSortedArrays(List<Integer> A, List<Integer> B,
List<Integer> C)
{
List<Integer> D = new ArrayList<>();
// Insert all elements from A into D
D.addAll(A);
// Insert all elements from B into D
D.addAll(B);
// Insert all elements from C into D
D.addAll(C);
// Sort the merged array in ascending order
Collections.sort(D);
return D;
}
// Driver code
public static void main(String[] args)
{
List<Integer> A = Arrays.asList(1, 2, 3, 5);
List<Integer> B = Arrays.asList(6, 7, 8, 9);
List<Integer> C = Arrays.asList(10, 11, 12);
// Merge three sorted arrays
List<Integer> D = mergeThreeSortedArrays(A, B, C);
// Print the merged and sorted array
for (int i = 0; i < D.size(); i++) {
System.out.print(D.get(i) + " ");
}
System.out.println();
}
}
Python
def mergeThreeSortedArrays(A, B, C):
D = []
# Insert all elements from A into D
for element in A:
D.append(element)
# Insert all elements from B into D
for element in B:
D.append(element)
# Insert all elements from C into D
for element in C:
D.append(element)
# Sort the merged array in ascending order
D.sort()
return D
# Driver code
A = [1, 2, 3, 5]
B = [6, 7, 8, 9]
C = [10, 11, 12]
# Merge three sorted arrays
D = mergeThreeSortedArrays(A, B, C)
# Print the merged and sorted array
for element in D:
print(element, end=" ")
print()
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
// Function to merge three sorted arrays
static List<int> MergeThreeSortedArrays(List<int> A,
List<int> B,
List<int> C)
{
List<int> D = new List<int>();
// Insert all elements from A into D
D.AddRange(A);
// Insert all elements from B into D
D.AddRange(B);
// Insert all elements from C into D
D.AddRange(C);
// Sort the merged array in ascending order
D.Sort();
return D;
}
// Driver code
static void Main()
{
List<int> A = new List<int>{ 1, 2, 3, 5 };
List<int> B = new List<int>{ 6, 7, 8, 9 };
List<int> C = new List<int>{ 10, 11, 12 };
// Merge three sorted arrays
List<int> D = MergeThreeSortedArrays(A, B, C);
// Print the merged and sorted array
foreach(int num in D) { Console.Write(num + " "); }
Console.WriteLine();
}
}
Javascript
// Function to merge three sorted arrays
function mergeThreeSortedArrays(A, B, C) {
let D = [];
// Insert all elements from A into D
for (let i = 0; i < A.length; i++) {
D.push(A[i]);
}
// Insert all elements from B into D
for (let i = 0; i < B.length; i++) {
D.push(B[i]);
}
// Insert all elements from C into D
for (let i = 0; i < C.length; i++) {
D.push(C[i]);
}
// Sort the merged array in ascending order
D.sort((a, b) => a - b);
return D;
}
// Driver code
function main() {
const A = [1, 2, 3, 5];
const B = [6, 7, 8, 9];
const C = [10, 11, 12];
// Merge three sorted arrays
const D = mergeThreeSortedArrays(A, B, C);
// Print the merged and sorted array
console.log(D.join(" "));
}
main();
Output1 2 3 5 6 7 8 9 10 11 12
Time Complexity: O( (n+m+p) * log(n+m+p) ), where n, m, and p are the lengths of the three arrays.
Space Complexity: O(n+m+p), where n, m, and p are the lengths of the three arrays. This is because vector D has been created of size (m+n+p).
Merge 3 Sorted Arrays by merging Two Arrays at a time:
The idea is to first merge two arrays and then merge the resultant with the third array.
Follow the steps below to solve the problem:
- First, merge the arr1 and arr2 using the idea mentioned in Merge Two Sorted Arrays
- Now merge the resultant array (from arr1 and arr2) with arr3.
- Print the answer array.
Pseudocode:
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)
Below is the implementation of the above approach:
C++
// C++ program to merge three sorted arrays
// by merging two at a time.
#include <iostream>
#include <vector>
using namespace std;
void printVector(const vector<int>& a)
{
for (auto e : a)
cout << e << " ";
cout << endl;
}
vector<int> mergeTwo(vector<int>& A,vector<int>& B)
{
// Get sizes of vectors
int m = A.size();
int n = B.size();
// Vector for storing Result
vector<int>D;
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<int> A = { 1, 2, 3, 5 };
vector<int> B = { 6, 7, 8, 9 };
vector<int> C = { 10, 11, 12 };
// First Merge A and B
vector<int>T = mergeTwo(A, B);
// Print Result after merging T with C
printVector(mergeTwo(T, C));
return 0;
}
Java
import java.util.*;
// Java program to merge three sorted arrays
// by merging two at a time.
class GFG {
static ArrayList<Integer> mergeTwo(List<Integer> A,
List<Integer> B)
{
// Get sizes of vectors
int m = A.size();
int n = B.size();
// ArrayList for storing Result
ArrayList<Integer> D
= new ArrayList<Integer>(m + n);
int i = 0, j = 0;
while (i < m && j < n) {
if (A.get(i) <= B.get(j))
D.add(A.get(i++));
else
D.add(B.get(j++));
}
// B has exhausted
while (i < m)
D.add(A.get(i++));
// A has exhausted
while (j < n)
D.add(B.get(j++));
return D;
}
// Driver code
public static void main(String[] args)
{
Integer[] a = { 1, 2, 3, 5 };
Integer[] b = { 6, 7, 8, 9 };
Integer[] c = { 10, 11, 12 };
List<Integer> A = Arrays.asList(a);
List<Integer> B = Arrays.asList(b);
List<Integer> C = Arrays.asList(c);
// First Merge A and B
ArrayList<Integer> T = mergeTwo(A, B);
// Print Result after merging T with C
ArrayList<Integer> ans = mergeTwo(T, C);
for (int i = 0; i < ans.size(); i++)
System.out.print(ans.get(i) + " ");
}
}
/* This code contributed by PrinciRaj1992 */
Python
# Python program to merge three sorted arrays
# by merging two at a time.
def mergearray(arr1, arr2):
i = 0
j = 0
arr = []
# Merge the two arrays in sorted order
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
arr.append(arr1[i])
i += 1
else:
arr.append(arr2[j])
j += 1
# Append the remaining elements of arr1
while i < len(arr1):
arr.append(arr1[i])
i += 1
# Append the remaining elements of arr2
while j < len(arr2):
arr.append(arr2[j])
j += 1
return arr
def mergethreesortedarray(arr1, arr2, arr3):
i = mergearray(arr1, arr2)
return mergearray(i, arr3)
print(mergethreesortedarray([1, 3, 5], [2, 4, 6, 8, 10], [7, 9, 11, 13, 15]))
C#
// C# program to merge three sorted arrays
// by merging two at a time.
using System;
using System.Collections.Generic;
public static class GFG {
static List<int> mergeTwo(List<int> A, List<int> B)
{
// Get sizes of vectors
int m = A.Count;
int n = B.Count;
// Vector for storing Result
List<int> D = new List<int>();
D.Capacity = m + n;
int i = 0;
int j = 0;
while (i < m && j < n) {
if (A[i] <= B[j]) {
D.Add(A[i++]);
}
else {
D.Add(B[j++]);
}
}
// B has exhausted
while (i < m) {
D.Add(A[i++]);
}
// A has exhausted
while (j < n) {
D.Add(B[j++]);
}
return D;
}
// Driver Code
public static void Main()
{
List<int> A = new List<int>() { 1, 2, 3, 5 };
List<int> B = new List<int>() { 6, 7, 8, 9 };
List<int> C = new List<int>() { 10, 11, 12 };
// First Merge A and B
List<int> T = mergeTwo(A, B);
// Print Result after merging T with C
List<int> ans = mergeTwo(T, C);
for (int i = 0; i < ans.Count; i++)
Console.Write(ans[i] + " ");
}
}
// This code is contributed by Aarti_Rathi
Javascript
// Javascript program to merge three sorted arrays
// by merging two at a time.
function mergeTwo(A, B)
{
// Get sizes of vectors
let m = A.length;
let n = B.length;
// Vector for storing Result
let D = [];
let i = 0, j = 0;
while (i < m && j < n) {
if (A[i] <= B[j])
D.push(A[i++]);
else
D.push(B[j++]);
}
// B has exhausted
while (i < m)
D.push(A[i++]);
// A has exhausted
while (j < n)
D.push(B[j++]);
return D;
}
// Driver Code
let A = [ 1, 2, 3, 5 ];
let B = [ 6, 7, 8, 9 ];
let C = [ 10, 11, 12 ];
// First Merge A and B
let T = mergeTwo(A, B);
// Print Result after merging T with C
console.log(mergeTwo(T, C));
Output1 2 3 5 6 7 8 9 10 11 12
Time Complexity: O(M+N+O) where m, n, o are the lengths of the 1st, 2nd, 3rd Array.
Auxiliary Space: O(M+N+O).
Merge 3 Sorted Arrays by merging Three arrays at a time:
The idea is to merge three arrays at the same time just like two arrays.
Follow the steps below to solve the problem:
- Initialize three pointers i, j, and k which are associated with arr1, arr2, and arr3 respectively
- Now check the smallest number from the i, j, and k indexes.
- Put that minimum value in the output array
- Increment the pointer which has minimum value by 1
- Perform these steps till any of the indexes reach the end of the array.
- After that check which two arrays don't reach the end and perform the same with those two arrays.
- At last, check which of the three arrays doesn't reach the end and put all the remaining elements of that array into the output array.
Pseudocode:
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
Below is the implementation of the above approach:
C++
// C++ program to merger three sorted arrays
// by merging three simultaneously.
#include <bits/stdc++.h>
using namespace std;
vector<int> mergeThree(vector<int>& A, vector<int>& B,
vector<int>& 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<int> 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<int> A = { 1, 2, 3, 5 };
vector<int> B = { 6, 7, 8, 9 };
vector<int> C = { 10, 11, 12 };
// Print Result
vector<int> ans = mergeThree(A, B, C);
for (auto x : ans)
cout << x << " ";
return 0;
}
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class Sorting {
public static void main(String[] args)
{
int A[] = { 1, 2, 3, 5 };
int B[] = { 6, 7, 8, 9 };
int C[] = { 10, 11, 12 };
// call the function to sort and print the sorted
// numbers
merge3sorted(A, B, C);
}
// Function to merge three sorted arrays
// A[], B[], C[]: input arrays
static void merge3sorted(int A[], int B[], int C[])
{
// creating an empty list to store sorted numbers
ArrayList<Integer> list = new ArrayList<Integer>();
int i = 0, j = 0, k = 0;
// using merge concept and trying to find
// smallest of three while all three arrays
// contains at least one element
while (i < A.length && j < B.length
&& k < C.length) {
int a = A[i];
int b = B[j];
int c = C[k];
if (a <= b && a <= c) {
list.add(a);
i++;
}
else if (b <= a && b <= c) {
list.add(b);
j++;
}
else {
list.add(c);
k++;
}
}
// next three while loop is to sort two
// of arrays if one of the three gets exhausted
while (i < A.length && j < B.length) {
if (A[i] < B[j]) {
list.add(A[i]);
i++;
}
else {
list.add(B[j]);
j++;
}
}
while (j < B.length && k < C.length) {
if (B[j] < C[k]) {
list.add(B[j]);
j++;
}
else {
list.add(C[k]);
k++;
}
}
while (i < A.length && k < C.length) {
if (A[i] < C[k]) {
list.add(A[i]);
i++;
}
else {
list.add(C[k]);
k++;
}
}
// if one of the array are left then
// simply appending them as there will
// be only largest element left
while (i < A.length) {
list.add(A[i]);
i++;
}
while (j < B.length) {
list.add(B[j]);
j++;
}
while (k < C.length) {
list.add(C[k]);
k++;
}
// finally print the list
for (Integer x : list)
System.out.print(x + " ");
} // merge3sorted closing braces
}
Python
# Python program to merge three sorted arrays
# simultaneously.
def merge_three(a, b, c):
(m, n, o) = (len(a), len(b), len(c))
i = j = k = 0
# Destination array
d = []
while i < m and j < n and k < o:
# Get Minimum element
mini = min(a[i], b[j], c[k])
# Add m to D
d.append(mini)
# Increment the source pointer which
# gives m
if a[i] == mini:
i += 1
elif b[j] == mini:
j += 1
elif c[k] == mini:
k += 1
# Merge a and b if c has exhausted
while i < m and j < n:
if a[i] <= b[j]:
d.append(a[i])
i += 1
else:
d.append(b[j])
j += 1
# Merge b and c if a has exhausted
while j < n and k < o:
if b[j] <= c[k]:
d.append(b[j])
j += 1
else:
d.append(c[k])
k += 1
# Merge a and c if b has exhausted
while i < m and k < o:
if a[i] <= c[k]:
d.append(a[i])
i += 1
else:
d.append(c[k])
k += 1
# Take elements from a if b and c
# have exhausted
while i < m:
d.append(a[i])
i += 1
# Take elements from b if a and c
# have exhausted
while j < n:
d.append(b[j])
j += 1
# Take elements from c if a and
# b have exhausted
while k < o:
d.append(c[k])
k += 1
return d
if __name__ == "__main__":
a = [1, 2, 3, 5]
b = [6, 7, 8, 9]
c = [10, 11, 12]
ans = merge_three(a, b, c)
for x in ans:
print(x, end=" ")
C#
// Online C# Editor for free
// Write, Edit and Run your C# code using C# Online Compiler
using System;
using System.Collections;
class Sorting {
// Function to merge three sorted arrays
// A[], B[], C[]: input arrays
static void merge3sorted(int[] A, int[] B, int[] C)
{
// creating an empty list to store sorted numbers
ArrayList list = new ArrayList();
int i = 0, j = 0, k = 0;
// using merge concept and trying to find
// smallest of three while all three arrays
// contains at least one element
while (i < A.Length && j < B.Length
&& k < C.Length) {
int a = A[i];
int b = B[j];
int c = C[k];
if (a <= b && a <= c) {
list.Add(a);
i++;
}
else if (b <= a && b <= c) {
list.Add(b);
j++;
}
else {
list.Add(c);
k++;
}
}
// next three while loop is to sort two
// of arrays if one of the three gets exhausted
while (i < A.Length && j < B.Length) {
if (A[i] < B[j]) {
list.Add(A[i]);
i++;
}
else {
list.Add(B[j]);
j++;
}
}
while (j < B.Length && k < C.Length) {
if (B[j] < C[k]) {
list.Add(B[j]);
j++;
}
else {
list.Add(C[k]);
k++;
}
}
while (i < A.Length && k < C.Length) {
if (A[i] < C[k]) {
list.Add(A[i]);
i++;
}
else {
list.Add(C[k]);
k++;
}
}
// if one of the array are left then
// simply appending them as there will
// be only largest element left
while (i < A.Length) {
list.Add(A[i]);
i++;
}
while (j < B.Length) {
list.Add(B[j]);
j++;
}
while (k < C.Length) {
list.Add(C[k]);
k++;
}
// Finally print the list
for (int x = 0; x < list.Count; x++)
Console.Write(list[x] + " ");
}
public static void Main(string[] args)
{
int[] A = { 1, 2, 3, 5 };
int[] B = { 6, 7, 8, 9 };
int[] C = { 10, 11, 12 };
// call the function to sort and print the sorted
// numbers
merge3sorted(A, B, C);
}
}
// This code is contributed by Aarti_Rathi
Javascript
// Javascript program to merger three sorted arrays
// by merging three simultaneously.
function printVector(a) {
console.log("[");
for (let e of a) {
console.log(e + " ");
}
console.log("]" + "<br>");
}
function mergeThree(A, B, C)
{
let m, n, o, i, j, k;
// Get Sizes of three vectors
m = A.length;
n = B.length;
o = C.length;
// Vector for storing output
let D = [];
i = j = k = 0;
while (i < m && j < n && k < o)
{
// Get minimum of a, b, c
let m = Math.min(Math.min(A[i], B[j]), C[k]);
// Put m in D
D.push(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(A[i]);
i++;
}
else {
D.push(B[j]);
j++;
}
}
// B has exhausted
while (i < m && k < o) {
if (A[i] <= C[k]) {
D.push(A[i]);
i++;
}
else {
D.push(C[k]);
k++;
}
}
// A has exhausted
while (j < n && k < o) {
if (B[j] <= C[k]) {
D.push(B[j]);
j++;
}
else {
D.push(C[k]);
k++;
}
}
// A and B have exhausted
while (k < o)
D.push(C[k++]);
// B and C have exhausted
while (i < m)
D.push(A[i++]);
// A and C have exhausted
while (j < n)
D.push(B[j++]);
return D;
}
// Driver Code
let A = [1, 2, 3, 5];
let B = [6, 7, 8, 9];
let C = [10, 11, 12];
// Print Result
printVector(mergeThree(A, B, C));
// This code is contributed by gfgking.
Output1 2 3 5 6 7 8 9 10 11 12
Time Complexity: O(M+N+O), Traversing over all the three arrays of size M, N, and O
Auxiliary Space: O(M+N+O), Space used for the output array
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 .
Optimization of the above approach:
The code written above can be shortened by the below code. Here we do not need to write code if any array gets exhausted. If any of the arrays get exhausted then store the large value(INT_MAX) in the variable which represents the value of that array. When all the pointers reach the end of their respective array return the resultant array.
Below is the implementation of the above approach:
C++
// C++ program to merge three sorted arrays
// by merging two at a time.
#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, 3, 5 };
vector<int> B = { 6, 7, 8, 9 };
vector<int> C = { 10, 11, 12 };
vector<int> final_ans = merge3sorted(A, B, C);
printeSorted(final_ans);
return 0;
}
// This code is contributed by Pushpesh raj
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.lang.*;
import java.util.*;
// Java program to merge three sorted arrays
// by merging two at a time.
// This code is contributed by Animesh Nag
class Solution {
// A[], B[], C[]: input arrays
// Function to merge three sorted lists into a single
// list.
static ArrayList<Integer> merge3sorted(int A[], int B[],
int C[])
{
ArrayList<Integer> ans = new ArrayList<Integer>();
int l1 = A.length;
int l2 = B.length;
int l3 = C.length;
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 = Integer.MAX_VALUE,
b = Integer.MAX_VALUE,
c = Integer.MAX_VALUE;
// 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.add(a);
i++;
}
// Checking if 'b' is the minimum
else if (b <= a && b <= c) {
ans.add(b);
j++;
}
// Checking if 'c' is the minimum
else {
if (c <= a && c <= b) {
ans.add(c);
k++;
}
}
}
return ans;
}
}
class GFG {
// Driver program to test above functions
public static void main(String[] args)
{
int[] A = { 1, 2, 3, 5 };
int[] B = { 6, 7, 8, 9 };
int[] C = { 10, 11, 12 };
Solution sol = new Solution();
ArrayList<Integer> final_ans
= sol.merge3sorted(A, B, C);
printeSorted(final_ans);
}
// A utility function to print array list
static void printeSorted(ArrayList<Integer> list)
{
for (Integer x : list)
System.out.print(x + " ");
}
}
Python
# Python program to merge three sorted arrays
# simultaneously.
def merge3sorted(A, B, C):
(l1, l2, l3) = (len(A), len(B), len(C))
i = j = k = 0
# Destination array
ans = []
while (i < l1 or j < l2 or k < l3):
# Assigning a, b, c with max values so that if
# any value is not present then also we can sort
# the array
a = 9999
b = 9999
c = 9999
# 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 and a <= c):
ans.append(a)
i += 1
# Checking if 'b' is the minimum
elif (b <= a and b <= c):
ans.append(b)
j += 1
# Checking if 'c' is the minimum
elif (c <= a and c <= b):
ans.append(c)
k += 1
return ans
if __name__ == "__main__":
A = [1, 2, 3, 5]
B = [6, 7, 8, 9]
C = [10, 11, 12]
ans = merge3sorted(A, B, C)
for x in ans:
print(x, end=" ")
# This code is contributed by Aarti_Rathi
C#
using System;
using System.Collections.Generic;
public static class GFG {
// C# program to merge three sorted arrays
// by merging two at a time.
// A[], B[], C[]: input arrays
// Function to merge three sorted lists into a single
// list.
public static List<int>
merge3sorted(List<int> A, List<int> B, List<int> C)
{
List<int> ans = new List<int>();
int l1 = A.Count;
int l2 = B.Count;
int l3 = C.Count;
int i = 0;
int j = 0;
int 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.MaxValue;
int b = int.MaxValue;
int c = int.MaxValue;
// 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.Add(a);
i++;
}
// Checking if 'b' is the minimum
else if (b <= a && b <= c) {
ans.Add(b);
j++;
}
// Checking if 'c' is the minimum
else {
if (c <= a && c <= b) {
ans.Add(c);
k++;
}
}
}
return new List<int>(ans);
}
// A utility function to print array list
public static void printeSorted(List<int> list)
{
foreach(var x in list)
{
Console.Write(x);
Console.Write(" ");
}
}
// Driver program to test above functions
public static void Main()
{
List<int> A = new List<int>() { 1, 2, 3, 5 };
List<int> B = new List<int>() { 6, 7, 8, 9 };
List<int> C = new List<int>() { 10, 11, 12 };
List<int> final_ans = merge3sorted(A, B, C);
printeSorted(new List<int>(final_ans));
}
}
// This code is contributed by Aarti_Rathi
Javascript
// javascript program to merge three sorted arrays
// by merging two at a time.
// A[], B[], C[]: input arrays
// Function to merge three sorted lists into a single
// list.
function merge3sorted(A, B, C)
{
var ans = new Array();
var l1 = A.length;
var l2 = B.length;
var l3 = C.length;
var i = 0;
var j = 0;
var 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.
var a = Number.MAX_VALUE;
var b = Number.MAX_VALUE;
var c = Number.MAX_VALUE;
// 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(a) > 0);
i++;
}
else if (b <= a && b <= c)
{
(ans.push(b) > 0);
j++;
}
else
{
if (c <= a && c <= b)
{
(ans.push(c) > 0);
k++;
}
}
}
return ans;
}
// A utility function to print array list
function printeSorted(list)
{
console.log("[ ");
for ( const x of list) {console.log(x + " ");}
console.log(" ]");
}
// Driver program to test above functions
var A = [1, 2, 3, 5];
var B = [6, 7, 8, 9];
var C = [10, 11, 12];
var final_ans = merge3sorted(A, B, C);
printeSorted(final_ans);
// This code is contributed by Aarti_Rathi
Output1 2 3 5 6 7 8 9 10 11 12
Time Complexity: O(l1+l2+l3), Traversing over all the three arrays of size l1, l2,and l3
Auxiliary Space: O(l1+l2+l3), Space used for the output array
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem