Sort elements of an array in increasing order of absolute difference of adjacent elements | Function to sort the elements of the array by difference ; Sorting the array ; Array to store the elements of the array ; Iterating over the length of the array to include each middle element of array ; Appending the middle element of the array ; Driver Code
function sortDiff ( arr , n ) { arr . sort ( function ( a , b ) { return a - b ; } ) ; let out = [ ] ; while ( n > 0 ) { out . push ( arr [ Math . floor ( n / 2 ) ] ) ; arr . splice ( Math . floor ( n / 2 ) , 1 ) ; n = n - 1 ; } for ( let i = 0 ; i < out . length ; i ++ ) document . write ( out [ i ] + " " ) ; } let arr = [ 8 , 1 , 2 , 3 , 0 ] ; let n = 5 ; sortDiff ( arr , n ) ;