Check if array can be sorted with one swap | A linear Python 3 program to check if array becomes sorted after one swap ; Find counts and positions of elements that are out of order . ; If there are more than two elements which are out of order . ; If all elements are sorted already ; Cases like { 1 , 5 , 3 , 4 , 2 } We swap 5 and 2. ; Cases like { 1 , 2 , 4 , 3 , 5 } ; Now check if array becomes sorted for cases like { 4 , 1 , 2 , 3 } ; Driver Code
def checkSorted ( n , arr ) : NEW_LINE INDENT first , second = 0 , 0 NEW_LINE count = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] < arr [ i - 1 ] : NEW_LINE INDENT count += 1 NEW_LINE if first == 0 : NEW_LINE INDENT first = i NEW_LINE DEDENT else : NEW_LINE INDENT second = i NEW_LINE DEDENT DEDENT DEDENT if count > 2 : NEW_LINE INDENT return False NEW_LINE DEDENT if count == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT if count == 2 : NEW_LINE INDENT ( arr [ first - 1 ] , arr [ second ] ) = ( arr [ second ] , arr [ first - 1 ] ) NEW_LINE DEDENT elif count == 1 : NEW_LINE INDENT ( arr [ first - 1 ] , arr [ first ] ) = ( arr [ first ] , arr [ first - 1 ] ) NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] < arr [ i - 1 ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 4 , 3 , 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