Rearrange array such that even index elements are smaller and odd index elements are greater | Swap ; Rearrange ; Utility that prints out an array in a line ; Driver Code
< ? php function swap ( & $ a , & $ b ) { $ temp = $ a ; $ a = $ b ; $ b = $ temp ; } function rearrange ( & $ arr , $ n ) { for ( $ i = 0 ; $ i < $ n - 1 ; $ i ++ ) { if ( $ i % 2 == 0 && $ arr [ $ i ] > $ arr [ $ i + 1 ] ) swap ( $ arr [ $ i ] , $ arr [ $ i + 1 ] ) ; if ( $ i % 2 != 0 && $ arr [ $ i ] < $ arr [ $ i + 1 ] ) swap ( $ arr [ $ i ] , $ arr [ $ i + 1 ] ) ; } } function printArray ( & $ arr , $ size ) { for ( $ i = 0 ; $ i < $ size ; $ i ++ ) echo $ arr [ $ i ] . " ▁ " ; echo " STRNEWLINE " ; } $ arr = array ( 6 , 4 , 2 , 1 , 8 , 3 ) ; $ n = sizeof ( $ arr ) ; echo " Before ▁ rearranging : ▁ STRNEWLINE " ; printArray ( $ arr , $ n ) ; rearrange ( $ arr , $ n ) ; echo " After ▁ rearranging : ▁ STRNEWLINE " ; printArray ( $ arr , $ n ) ; ? >