Sort an Array based on the absolute difference of adjacent elements | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sortedAdjacentDifferences ( int arr [ ] , int n ) { int ans [ n ] ; sort ( arr + 0 , arr + n ) ; int l = 0 , r = n - 1 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( i % 2 ) { ans [ i ] = arr [ l ] ; l ++ ; } else { ans [ i ] = arr [ r ] ; r -- ; } } for ( int i = 0 ; i < n ; i ++ ) { cout << ans [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 5 , -2 , 4 , 8 , 6 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortedAdjacentDifferences ( arr , n ) ; return 0 ; }