Sort an array according to absolute difference with a given value " using ▁ constant ▁ extra ▁ space " | Javascript program to sort an array based on absolute difference with a given value x . ; Below lines are similar to insertion sort ; Insert arr [ i ] at correct place ; Function to print the array ; Driver code
function arrange ( arr , n , x ) { for ( let i = 1 ; i < n ; i ++ ) { let diff = Math . abs ( arr [ i ] - x ) ; let j = i - 1 ; if ( Math . abs ( arr [ j ] - x ) > diff ) { let temp = arr [ i ] ; while ( j >= 0 && Math . abs ( arr [ j ] - x ) > diff ) { arr [ j + 1 ] = arr [ j ] ; j -- ; } arr [ j + 1 ] = temp ; } } } function print ( arr , n ) { for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; } let arr = [ 10 , 5 , 3 , 9 , 2 ] ; let n = arr . length ; let x = 7 ; arrange ( arr , n , x ) ; print ( arr , n ) ;