Sort Array such that smallest is at 0 th index and next smallest it at last index and so on | C ++ program for the above approach ; Function to perform the rearrangement ; Initialize variables ; Loop until i crosses j ; This check is to find the minimum values in the ascending order ; Condition to alternatively iterate variable i and j ; Perform swap operation ; Increment i ; Assign the value of min ; Perform swap ; Decrement i ; Assign the value of min ; Print the array ; Driver Code ; Given Array arr [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void rearrange ( int a [ ] , int N ) { int i = 0 , j = N - 1 ; int min = 0 , k , x = 0 , temp ; while ( i < j ) { for ( k = i ; k <= j ; k ++ ) { if ( a [ k ] < a [ min ] ) min = k ; } if ( x % 2 == 0 ) { temp = a [ i ] ; a [ i ] = a [ min ] ; a [ min ] = temp ; i ++ ; min = i ; } else { temp = a [ j ] ; a [ j ] = a [ min ] ; a [ min ] = temp ; j -- ; min = j ; } x ++ ; } for ( i = 0 ; i < N ; i ++ ) cout << a [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 1 , 3 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; rearrange ( arr , N ) ; return 0 ; }