Java Program for Merge 3 Sorted Arrays
Last Updated :
27 Apr, 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
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
System.out.println(mergeTwo(T, C));
}
}
/* This code contributed by PrinciRaj1992 */
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:
Java
import java.util.*;
import java.io.*;
import java.lang.*;
class Sorting {
public static void main(String[] args)
{
int A[] = { 1, 2, 41, 52, 84 };
int B[] = { 1, 2, 41, 52, 67 };
int C[] = { 1, 2, 41, 52, 67, 85 };
// 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
}
Output[1 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.
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 .
Please refer complete article on Merge 3 Sorted Arrays for more details!
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Java Tutorial
Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts
Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers
Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read