Efficiently merging two sorted arrays with O ( 1 ) extra space |  ; Now traverse the array1 and if arr2 first element is less than arr1 then swap ; Swap ; We will store the firstElement of array2 and left shift all the element and store the firstElement in arr2 [ k - 1 ] ; Read the arr1 ; Read the arr2 ; Driver Code
function mergeArray ( arr1 , arr2 , n , m ) { for ( let i = 0 ; i < n ; i ++ ) { if ( arr1 [ i ] > arr2 [ 0 ] ) { let temp = arr1 [ i ] ; arr1 [ i ] = arr2 [ 0 ] ; arr2 [ 0 ] = temp ; let firstElement = arr2 [ 0 ] ; let k ; for ( k = 1 ; k < m && arr2 [ k ] < firstElement ; k ++ ) { arr2 [ k - 1 ] = arr2 [ k ] ; } arr2 [ k - 1 ] = firstElement ; } } for ( let i = 0 ; i < n ; i ++ ) { document . write ( arr1 [ i ] + " " ) ; } document . write ( " " ) ; for ( let i = 0 ; i < m ; i ++ ) { document . write ( arr2 [ i ] + " " ) ; } } let arr1 = [ 1 , 3 , 5 , 7 ] ; let arr2 = [ 0 , 2 , 6 , 8 , 9 ] ; let n = 4 , m = 5 ; mergeArray ( arr1 , arr2 , n , m ) ;