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 ; Printing the elements in decreasing order ; Increasing the number of elements to printed in next iteration ; Driver code
function printArray ( arr , n ) { arr . sort ( ) ; let l = 0 , r = n - 1 , flag = 0 , i ; let k = 2 ; while ( l <= r ) { if ( flag == 0 ) { for ( i = l ; i < l + k && i <= r ; i ++ ) document . write ( arr [ i ] + " " ) ; flag = 1 ; l = i ; } else { for ( i = r ; i > r - k && i >= l ; i -- ) document . write ( arr [ i ] + " " ) ; flag = 0 ; r = i ; } k ++ ; } } let n = 6 ; let arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] ; printArray ( arr , n ) ;