Sorting all array elements except one | Python3 program to sort all elements except element at index k . ; Move k - th element to end ; Sort all elements except last ; Store last element ( originally k - th ) ; Move all elements from k - th to one position ahead . ; Restore k - th element ; Driver code
def sortExcept ( arr , k , n ) : NEW_LINE INDENT arr [ k ] , arr [ - 1 ] = arr [ - 1 ] , arr [ k ] NEW_LINE arr = sorted ( arr , key = lambda i : ( i is arr [ - 1 ] , i ) ) NEW_LINE last = arr [ - 1 ] NEW_LINE i = n - 1 NEW_LINE while i > k : NEW_LINE INDENT arr [ i ] = arr [ i - 1 ] NEW_LINE i -= 1 NEW_LINE DEDENT arr [ k ] = last NEW_LINE return arr NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 10 , 4 , 11 , 7 , 6 , 20 ] NEW_LINE k = 2 NEW_LINE n = len ( a ) NEW_LINE a = sortExcept ( a , k , n ) NEW_LINE print ( " ▁ " . join ( list ( map ( str , a ) ) ) ) NEW_LINE DEDENT