Print array elements in alternatively increasing and decreasing order | C ++ program to print array elements in alternative 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArray ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int l = 0 , r = n - 1 , flag = 0 , i ; int k = 2 ; while ( l <= r ) { if ( flag == 0 ) { for ( i = l ; i < l + k && i <= r ; i ++ ) cout << arr [ i ] << " ▁ " ; flag = 1 ; l = i ; } { for ( i = r ; i > r - k && i >= l ; i -- ) cout << arr [ i ] << " ▁ " ; flag = 0 ; r = i ; } k ++ ; } } int main ( ) { int n = 6 ; int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; printArray ( arr , n ) ; return 0 ; }