human
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"
How can the above be solved in Python?
assistant
#Here is code to check if array can be sorted with one swap and the other steps required.
 def checkSorted ( n , arr ) :
	first , second = 0 , 0
	count = 0
	for i in range ( 1 , n ) :
		if arr [ i ] < arr [ i - 1 ] :
			count += 1
			if first == 0 :
				first = i
			else :
				second = i
	if count > 2 :
		return False
	if count == 0 :
		return True
	if count == 2 :
		( arr [ first - 1 ] , arr [ second ] ) = ( arr [ second ] , arr [ first - 1 ] )
	elif count == 1 :
		( arr [ first - 1 ] , arr [ first ] ) = ( arr [ first ] , arr [ first - 1 ] )
	for i in range ( 1 , n ) :
		if arr [ i ] < arr [ i - 1 ] :
			return False
	return True
if __name__ == ' _ _ main _ _ ' :
	arr = [ 1 , 4 , 3 , 2 ]
	n = len ( arr )
	if checkSorted ( n , arr ) :
		print ( " Yes " )
	else :
		print ( " No " )