Merge two sorted arrays with O ( 1 ) extra space | Merge ar1 [ ] and ar2 [ ] with O ( 1 ) extra space ; Iterate through all elements of ar2 [ ] starting from the last element ; Find the smallest element greater than ar2 [ i ] . Move all elements one position ahead till the smallest greater element is not found ; If there was a greater element ; Driver program
< ? php function merge ( & $ ar1 , & $ ar2 , $ m , $ n ) { for ( $ i = $ n - 1 ; $ i >= 0 ; $ i -- ) { $ last = $ ar1 [ $ m - 1 ] ; for ( $ j = $ m - 2 ; $ j >= 0 && $ ar1 [ $ j ] > $ ar2 [ $ i ] ; $ j -- ) $ ar1 [ $ j + 1 ] = $ ar1 [ $ j ] ; if ( $ j != $ m - 2 $ last > $ ar2 [ $ i ] ) { $ ar1 [ $ j + 1 ] = $ ar2 [ $ i ] ; $ ar2 [ $ i ] = $ last ; } } } $ ar1 = array ( 1 , 5 , 9 , 10 , 15 , 20 ) ; $ ar2 = array ( 2 , 3 , 8 , 13 ) ; $ m = sizeof ( $ ar1 ) / sizeof ( $ ar1 [ 0 ] ) ; $ n = sizeof ( $ ar2 ) / sizeof ( $ ar2 [ 0 ] ) ; merge ( $ ar1 , $ ar2 , $ m , $ n ) ; echo " First Array : " for ( $ i = 0 ; $ i < $ m ; $ i ++ ) echo $ ar1 [ $ i ] . " ▁ " ; echo " Second Array : " for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo $ ar2 [ $ i ] . " ▁ " ; return 0 ; ? >