Rearrange array such that arr [ i ] >= arr [ j ] if i is even and arr [ i ] <= arr [ j ] if i is odd and j < i | function to rearrange the array ; total even positions ; total odd positions ; copy original array in an auxiliary array ; sort the auxiliary array ; fill up odd position in original array ; fill up even positions in original array ; display array ; Driver code
< ? php function rearrangeArr ( & $ arr , $ n ) { $ evenPos = intval ( $ n / 2 ) ; $ oddPos = $ n - $ evenPos ; $ tempArr = array_fill ( 0 , $ n , NULL ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ tempArr [ $ i ] = $ arr [ $ i ] ; sort ( $ tempArr ) ; $ j = $ oddPos - 1 ; for ( $ i = 0 ; $ i < $ n ; $ i += 2 ) { $ arr [ $ i ] = $ tempArr [ $ j ] ; $ j -- ; } $ j = $ oddPos ; for ( $ i = 1 ; $ i < $ n ; $ i += 2 ) { $ arr [ $ i ] = $ tempArr [ $ j ] ; $ j ++ ; } for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo $ arr [ $ i ] . " ▁ " ; } $ arr = array ( 1 , 2 , 3 , 4 , 5 , 6 , 7 ) ; $ size = sizeof ( $ arr ) ; rearrangeArr ( $ arr , $ size ) ; ? >