Javascript program to merge k sorted // arrays of size n each.
// This function takes an array of
// arrays as an argument and
// All arrays are assumed to be sorted.
// It merges them together and prints
// the final sorted output.
function mergeKArrays(arr , a, output)
{
var c = 0;
// traverse the matrix
for (i = 0; i < a; i++) {
for (j = 0; j < 4; j++)
output = arr[i][j];
}
// sort the array
output.sort((a,b)=>a-b);
}
// A utility function to print array elements
function printArray(arr , size) {
for (i = 0; i < size; i++)
document.write(arr[i] + " ");
}
// Driver program to test above functions
var arr = [ [ 2, 6, 12, 34 ],
[ 1, 9, 20, 1000 ],
[ 23, 34, 90, 2000 ] ];
var K = 4;
var N = 3;
var output = Array(N * K).fill(0);
mergeKArrays(arr, N, output);
document.write("Merged array is ");
printArray(output, N * K);
Output Merged array is 1 2 6 9 12 20 23 34 34 90 1000 2000 [Time Complexity:: O(N * K * log (NK))], Since the resulting array is of size NK. Space Complexity: O(N * K), The output array is of size N * K.
Merge K sorted arrays using merging: The process begins with merging arrays into groups of two. After the first merge, there will be K/2 arrays remaining. Again merge arrays in groups, now K/4 arrays will be remaining. This is similar to merge sort. Divide K arrays into two halves containing an equal number of arrays until there are two arrays in a group. This is followed by merging the arrays in a bottom-up