Rearrange Odd and Even values in Alternate Fashion in Ascending Order | PHP implementation of the above approach ; Sort the array ; $v1 = array ( ) ; to insert even values $v2 = array ( ) ; to insert odd values ; Set flag to true if first element is even ; Start rearranging array ; If first element is even ; Else , first element is Odd ; Print the rearranged array ; Driver code
< ? php function AlternateRearrange ( $ arr , $ n ) { sort ( $ arr ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) if ( $ arr [ $ i ] % 2 == 0 ) array_push ( $ v1 , $ arr [ $ i ] ) ; else array_push ( $ v2 , $ arr [ $ i ] ) ; $ index = 0 ; $ i = 0 ; $ j = 0 ; $ flag = false ; if ( $ arr [ 0 ] % 2 == 0 ) $ flag = true ; while ( $ index < $ n ) { if ( $ flag == true ) { $ arr [ $ index ++ ] = $ v1 [ $ i ++ ] ; $ flag = ! $ flag ; } else { $ arr [ $ index ++ ] = $ v2 [ $ j ++ ] ; $ flag = ! $ flag ; } } for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo $ arr [ $ i ] , " ▁ " ; } $ arr = array ( 9 , 8 , 13 , 2 , 19 , 14 ) ; $ n = sizeof ( $ arr ) ; AlternateRearrange ( $ arr , $ n ) ; ? >