Generate all possible sorted arrays from alternate elements of two given sorted arrays | Function to generates and prints all sorted arrays from alternate elements of ' A [ i . . m - 1 ] ' and ' B [ j . . n - 1 ] ' If ' flag ' is true , then current element is to be included from A otherwise from B . ' len ' is the index in output array C [ ] . We print output array each time before including a character from A only if length of output array is greater than 0. We try than all possible combinations ; Include valid element from A ; Print output if there is at least one ' B ' in output array ' C ' ; Recur for all elements of A after current index ; this block works for the very first call to include the first element in the output array ; don 't increment lem as B  is included yet ; include valid element from A and recur ; Include valid element from B and recur ; Wrapper function ; output array ; A utility function to print an array ; Driver Code
< ? php function generateUtil ( & $ A , & $ B , & $ C , $ i , $ j , $ m , $ n , $ len , $ flag ) { if ( $ flag ) { if ( $ len ) printArr ( $ C , $ len + 1 ) ; for ( $ k = $ i ; $ k < $ m ; $ k ++ ) { if ( ! $ len ) { $ C [ $ len ] = $ A [ $ k ] ; generateUtil ( $ A , $ B , $ C , $ k + 1 , $ j , $ m , $ n , $ len , ! $ flag ) ; } else { if ( $ A [ $ k ] > $ C [ $ len ] ) { $ C [ $ len + 1 ] = $ A [ $ k ] ; generateUtil ( $ A , $ B , $ C , $ k + 1 , $ j , $ m , $ n , $ len + 1 , ! $ flag ) ; } } } } else { for ( $ l = $ j ; $ l < $ n ; $ l ++ ) { if ( $ B [ $ l ] > $ C [ $ len ] ) { $ C [ $ len + 1 ] = $ B [ $ l ] ; generateUtil ( $ A , $ B , $ C , $ i , $ l + 1 , $ m , $ n , $ len + 1 , ! $ flag ) ; } } } } function generate ( & $ A , & $ B , $ m , $ n ) { $ C = array_fill ( 0 , ( $ m + $ n ) , NULL ) ; generateUtil ( $ A , $ B , $ C , 0 , 0 , $ m , $ n , 0 , true ) ; } function printArr ( & $ arr , $ n ) { for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo $ arr [ $ i ] . " ▁ " ; echo " STRNEWLINE " ; } $ A = array ( 10 , 15 , 25 ) ; $ B = array ( 5 , 20 , 30 ) ; $ n = sizeof ( $ A ) ; $ m = sizeof ( $ B ) ; generate ( $ A , $ B , $ n , $ m ) ; ? >