Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Merge k sorted arrays in Java
We are given an ‘n’ number of arrays, let's say we take three arrays i.e. arr1[], arr2[] and arr3[] of integer type. The task is to merge all the given integer arrays in such a manner that the resultant array is sorted in the runtime only.
Let us understand with example
Input −
Int
a[]={21,22,23,24};
int b[ ] ={28,31,35}
Output −int resultant[ ]={21,22,23,24,28,31,35}.
Explanation − The array elements are compared before they are added and added according to their suitable position in the resultant array.
Input −
int
a[]={1,3,5,7,9,11,13};
int b[ ] ={14,16,18}
int c[ ] ={19,20,21,22}
Output − int resultant[ ]={1,3,5,7,9,11,13,14,16,18,19,20,21,22}.
Explanation −The array elements are compared before they are added and added according to their suitable position in the resultant array.
Approach used in the below program is as follows −
Input three integer arrays let’s say, arr1[], arr2[] and arr3[] and a resultant array as result[] and set it to the call to a method as mergeSortedArray(new int[][] { arr1, arr2, arr3 })
-
Inside the method mergeSortedArray(new int[][] { arr1, arr2, arr3 })
Create a variable as a queue of type priority queue and a variable as total and set it to 0.
Start loop FOR from i to 0 till length of an array and add element from bucket of an array to the variable declared as queue and set total to total + arr[i].length.
Set m to 0 and declare result[] integer array.
Start while queue.isEmpty() = false then set ArrayBucket ac to queue.poll(), result[m++] to ac.arr[ac.index] and check IF ac.index less than ac.arr.length - 1 then set queue.add(new ArrayBucket(ac.arr, ac.index + 1))
Return result
Example
import java.util.Arrays; import java.util.PriorityQueue; class ArrayBucket implements Comparable{ int[] arr; int index; public ArrayBucket(int[] arr, int index){ this.arr = arr; this.index = index; } @Override public int compareTo(ArrayBucket o){ return this.arr[this.index] - o.arr[o.index]; } } public class testClass{ public static int[] mergeSortedArray(int[][] arr){ PriorityQueue queue = new PriorityQueue (); int total = 0; for (int i = 0; i Output
If we run the above code it will generate the following Output
The final merged sorted array is :-[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
