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
Java Program to Merge Two Arrays
In Java, merging two arrays is a good programming question. We have given two arrays, and our task is to merge them, and after merging, we need to put the result back into another array. In this article, we are going to discuss different ways we can use to merge two arrays in Java.Let's now see the
5 min read
Java Program for Iterative Merge Sort
Following is a typical recursive implementation of Merge Sort that uses last element as pivot. Java // Recursive Java Program for merge sort import java.util.Arrays; public class GFG { public static void mergeSort(int[] array) { if(array == null) { return; } if(array.length > 1) { int mid = array
2 min read
Java Program for Menu Driven Sorting of Array
In Java, sorting an array consists of arranging the elements in a particular order, such as ascending or descending. This can be achieved using various algorithms like Bubble Sort, Selection Sort, or Insertion Sort. A menu-driven program allows users to select the desired sorting method dynamically.
7 min read
Java Program to Sort an array in wave form
Given an unsorted array of integers, sort the array into a wave-like array. An array 'arr[0..n-1]' is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= ..... Examples: Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80} Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} OR
4 min read
Java Program For Merge Sort For Doubly Linked List
Given a doubly linked list, write a function to sort the doubly linked list in increasing order using merge sort.For example, the following doubly linked list should be changed to 24810 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Merge sort for singly linked l
3 min read
Java Array Programs
An array is a data structure consisting of a collection of elements (values or variables), of the same memory size, each identified by at least one array index or key. An array is a linear data structure that stores similar elements (i.e. elements of similar data type) that are stored in contiguous
4 min read
Java Program For Sorting An Array Of 0s, 1s and 2s
Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.Examples: Input: {0, 1, 2, 0, 1, 2} Output: {0, 0, 1, 1, 2, 2} Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1} Output: {0, 0, 0,
6 min read
Java Program for Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. Bubble Sort in Java is not the best method to sort an array but is one of the most basic implementations for one to learn. In this article, we will learn how to write
2 min read
Java Program for QuickSort
Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of QuickSort that pick pivot in different ways.Always pick first element as pivot.Always pick last element as pivot (im
2 min read
Java Program for ShellSort
In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h'th element is sorted. Java // Java implementation of ShellSort class ShellSort { /* An utility function to print array of si
2 min read