Check if array can be sorted with one swap | A linear Python 3 program to check if array becomes sorted after one swap ; Create a sorted copy of original array ; Check if 0 or 1 swap required to get the sorted array ; Driver Code
def checkSorted ( n , arr ) : NEW_LINE INDENT b = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT b . append ( arr [ i ] ) NEW_LINE DEDENT b . sort ( ) NEW_LINE ct = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] != b [ i ] : NEW_LINE INDENT ct += 1 NEW_LINE DEDENT DEDENT if ct == 0 or ct == 2 : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 5 , 3 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE if checkSorted ( n , arr ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT