Rearrange the Array to maximize the elements which is smaller than both its adjacent elements | 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 ; Input ; Function call
function maximumIndices ( arr , N ) { let temp = new Array ( N ) . fill ( 0 ) ; let maxIndices = parseInt ( ( N - 1 ) / 2 ) ; arr . sort ( function ( a , b ) { return a - b ; } ) for ( let i = 0 ; i < maxIndices ; i ++ ) { temp [ 2 * i + 1 ] = arr [ i ] ; } let j = 0 ; for ( let i = maxIndices ; i < N ; ) { if ( temp [ j ] == 0 ) { temp [ j ] = arr [ i ] ; i ++ ; } j ++ ; } for ( let i = 0 ; i < N ; i ++ ) { document . write ( temp [ i ] + " " ) ; } } let arr = [ 1 , 2 , 3 , 4 ] ; let N = arr . length ; maximumIndices ( arr , N ) ;