# 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<ArrayBucket>{
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<ArrayBucket> queue = new
PriorityQueue<ArrayBucket>();
int total = 0;
for (int i = 0; i < arr.length; i++){
total = total + arr[i].length;
}
int m = 0;
int result[] = new int[total];
while (!queue.isEmpty()){
ArrayBucket ac = queue.poll();
result[m++] = ac.arr[ac.index];
if (ac.index < ac.arr.length - 1){
}
}
return result;
}
public static void main(String[] args){
int[] arr1 = { 1, 3, 5, 7 };
int[] arr2 = { 2, 4, 6, 8 };
int[] arr3 = { 0, 9, 10, 11 };
int[] result = mergeSortedArray(new int[][] { arr1, arr2, arr3 });
System.out.println("The final merged sorted array is :- "+Arrays.toString(result));
}
}

## 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]