Sort an Array based on the absolute difference of adjacent elements | Java implementation of the above approach ; Function that arrange the array such that all absolute difference between adjacent element are sorted ; To store the resultant array ; Sorting the given array in ascending order ; Variable to represent left and right ends of the given array ; Traversing the answer array in reverse order and arrange the array elements from arr [ ] in reverse order ; Inserting elements in zig - zag manner ; Displaying the resultant array ; Driver Code ; Function Call
import java . util . * ; class GFG { static void sortedAdjacentDifferences ( int arr [ ] , int n ) { int [ ] ans = new int [ n ] ; Arrays . sort ( arr ) ; int l = 0 , r = n - 1 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( i % 2 == 1 ) { ans [ i ] = arr [ l ] ; l ++ ; } else { ans [ i ] = arr [ r ] ; r -- ; } } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( ans [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 5 , - 2 , 4 , 8 , 6 , 4 , 5 } ; int n = arr . length ; sortedAdjacentDifferences ( arr , n ) ; } }