Merge an array of size n into another array of size m + n | Assuming - 1 is filled for the places where element is not available ; Function to move m elements at the end of array mPlusN [ ] ; Merges array N [ ] of size n into array mPlusN [ ] of size m + n ; Current index of i / p part of mPlusN [ ] ; Current index of N [ ] ; Current index of output mPlusN [ ] ; Take an element from mPlusN [ ] if a ) value of the picked element is smaller and we have not reached end of it b ) We have reached end of N [ ] ; Otherwise take element from N [ ] ; Utility that prints out an array on a line ; Initialize arrays ; Move the m elements at the end of mPlusN ; Merge N [ ] into mPlusN [ ] ; Print the resultant mPlusN
< ? php $ NA = -1 ; function moveToEnd ( & $ mPlusN , $ size ) { global $ NA ; $ j = $ size - 1 ; for ( $ i = $ size - 1 ; $ i >= 0 ; $ i -- ) if ( $ mPlusN [ $ i ] != $ NA ) { $ mPlusN [ $ j ] = $ mPlusN [ $ i ] ; $ j -- ; } } function merge ( & $ mPlusN , & $ N , $ m , $ n ) { $ i = $ n ; $ j = 0 ; $ k = 0 ; while ( $ k < ( $ m + $ n ) ) { if ( ( $ j == $ n ) || ( $ i < ( $ m + $ n ) && $ mPlusN [ $ i ] <= $ N [ $ j ] ) ) { $ mPlusN [ $ k ] = $ mPlusN [ $ i ] ; $ k ++ ; $ i ++ ; } else { $ mPlusN [ $ k ] = $ N [ $ j ] ; $ k ++ ; $ j ++ ; } } } function printArray ( & $ arr , $ size ) { for ( $ i = 0 ; $ i < $ size ; $ i ++ ) echo $ arr [ $ i ] . " ▁ " ; echo " STRNEWLINE " ; } $ mPlusN = array ( 2 , 8 , $ NA , $ NA , $ NA , 13 , $ NA , 15 , 20 ) ; $ N = array ( 5 , 7 , 9 , 25 ) ; $ n = sizeof ( $ N ) ; $ m = sizeof ( $ mPlusN ) - $ n ; moveToEnd ( $ mPlusN , $ m + $ n ) ; merge ( $ mPlusN , $ N , $ m , $ n ) ; printArray ( $ mPlusN , $ m + $ n ) ; ? >