Rearrange the Array to maximize the elements which is smaller than both its adjacent elements | Java 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
import java . io . * ; import java . util . * ; class GFG { public static void maximumIndices ( int arr [ ] , int N ) { int [ ] temp = new int [ N ] ; int maxIndices = ( N - 1 ) / 2 ; Arrays . sort ( arr ) ; 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 ++ ) { System . out . print ( temp [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = 4 ; maximumIndices ( arr , N ) ; } }