Rearrange the Array to maximize the elements which is smaller than both its adjacent elements | C ++ program for the above approach ; Function to rearrange array such that count of element that are smaller than their adjacent elements is maximum ; Stores the rearranged array ; Stores the maximum count of elements ; Sort the given array ; Place the smallest ( N - 1 ) / 2 elements at odd indices ; Placing the rest of the elements at remaining indices ; If no element of the array has been placed here ; Print the resultant array ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumIndices ( int arr [ ] , int N ) { int temp [ N ] = { 0 } ; int maxIndices = ( N - 1 ) / 2 ; sort ( arr , arr + N ) ; for ( int i = 0 ; i < maxIndices ; i ++ ) { temp [ 2 * i + 1 ] = arr [ i ] ; } int j = 0 ; for ( int i = maxIndices ; i < N ; ) { if ( temp [ j ] == 0 ) { temp [ j ] = arr [ i ] ; i ++ ; } j ++ ; } for ( int i = 0 ; i < N ; i ++ ) { cout << temp [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximumIndices ( arr , N ) ; return 0 ; }