Print array elements in alternatively increasing and decreasing order | Function to print array elements in alternative increasing and decreasing order ; First sort the array in increasing order ; start with 2 elements in increasing order ; till all the elements are not printed ; printing the elements in increasing order ; else printing the elements in decreasing order ; increasing the number of elements to printed in next iteration ; Driver Code
< ? php function printArray ( $ arr , $ n ) { sort ( $ arr ) ; $ l = 0 ; $ r = $ n - 1 ; $ flag = 0 ; $ k = 2 ; while ( $ l <= $ r ) { if ( $ flag == 0 ) { for ( $ i = $ l ; $ i < $ l + $ k && $ i <= $ r ; $ i ++ ) echo $ arr [ $ i ] , " ▁ " ; $ flag = 1 ; $ l = $ i ; } { for ( $ i = $ r ; $ i > $ r - $ k && $ i >= $ l ; $ i -- ) echo $ arr [ $ i ] , " ▁ " ; $ flag = 0 ; $ r = $ i ; } $ k ++ ; } } $ n = 6 ; $ arr = array ( 1 , 2 , 3 , 4 , 5 , 6 ) ; printArray ( $ arr , $ n ) ; ? >