Merge k sorted arrays | Set 1 | 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 . ; traverse the matrix ; sort the array ; A utility function to print array elements ; Driver program to test above functions
function mergeKArrays ( arr , a , output ) { var c = 0 ; for ( i = 0 ; i < a ; i ++ ) { for ( j = 0 ; j < 4 ; j ++ ) output [ c ++ ] = arr [ i ] [ j ] ; } output . sort ( ( a , b ) => a - b ) ; } function printArray ( arr , size ) { for ( i = 0 ; i < size ; i ++ ) document . write ( arr [ i ] + " " ) ; } 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 ( " " ) ; printArray ( output , n * k ) ;