Sort an array according to absolute difference with given value | Function to sort an array according absolute difference with x . ; Store values in a map with the difference with X as key ; Update the values of array ; Function to print the array ; Driver code
def rearrange ( arr , n , x ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT m [ arr [ i ] ] = abs ( x - arr [ i ] ) NEW_LINE DEDENT m = { k : v for k , v in sorted ( m . items ( ) , key = lambda item : item [ 1 ] ) } NEW_LINE i = 0 NEW_LINE for it in m . keys ( ) : NEW_LINE INDENT arr [ i ] = it NEW_LINE i += 1 NEW_LINE DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 5 , 3 , 9 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE x = 7 NEW_LINE rearrange ( arr , n , x ) NEW_LINE printArray ( arr , n ) NEW_LINE DEDENT