Store values in a map with the difference with X as key
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