Sort an array according to absolute difference with a given value " using ▁ constant ▁ extra ▁ space " | Python 3 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
def arrange ( arr , n , x ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT diff = abs ( arr [ i ] - x ) NEW_LINE j = i - 1 NEW_LINE if ( abs ( arr [ j ] - x ) > diff ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE while ( abs ( arr [ j ] - x ) > diff and j >= 0 ) : NEW_LINE INDENT arr [ j + 1 ] = arr [ j ] NEW_LINE j -= 1 NEW_LINE DEDENT arr [ j + 1 ] = temp NEW_LINE DEDENT DEDENT DEDENT def print_1 ( 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 arrange ( arr , n , x ) NEW_LINE print_1 ( arr , n ) NEW_LINE DEDENT