Sort integers in array according to their distance from the element K | Function to get sorted array based on their distance from given integer K ; Vector to store respective elements with their distance from integer K ; Find the position of integer K ; Insert the elements with their distance from K in vector ; Element at distance 0 ; Elements at left side of K ; Elements at right side of K ; Print the vector content in sorted order ; Sort elements at same distance ; Print elements at distance i from K ; Driver code
def distanceSort ( arr , K , n ) : NEW_LINE INDENT vd = [ [ ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == K ) : NEW_LINE INDENT pos = i NEW_LINE break NEW_LINE DEDENT DEDENT i = pos - 1 NEW_LINE j = pos + 1 NEW_LINE vd [ 0 ] . append ( arr [ pos ] ) NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT vd [ pos - i ] . append ( arr [ i ] ) NEW_LINE i -= 1 NEW_LINE DEDENT while ( j < n ) : NEW_LINE INDENT vd [ j - pos ] . append ( arr [ j ] ) NEW_LINE j += 1 NEW_LINE DEDENT for i in range ( max ( pos , n - pos - 1 ) + 1 ) : NEW_LINE INDENT vd [ i ] . sort ( reverse = False ) NEW_LINE for element in vd [ i ] : NEW_LINE INDENT print ( element , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 14 , 1101 , 10 , 35 , 0 ] NEW_LINE K = 35 NEW_LINE n = len ( arr ) NEW_LINE distanceSort ( arr , K , n ) NEW_LINE DEDENT