Sort an Array based on the absolute difference of adjacent elements | 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
function sortedAdjacentDifferences ( arr , n ) { let ans = new Array ( n ) ; arr . sort ( ) ; let l = 0 , r = n - 1 ; for ( let i = n - 1 ; i >= 0 ; i -- ) { if ( i % 2 ) { ans [ i ] = arr [ l ] ; l ++ ; } else { ans [ i ] = arr [ r ] ; r -- ; } } for ( let i = 0 ; i < n ; i ++ ) { document . write ( ans [ i ] + " " ) ; } } let arr = [ 5 , - 2 , 4 , 8 , 6 , 4 , 5 ] ; let n = arr . length ; sortedAdjacentDifferences ( arr , n ) ;