# Check if array can be sorted with one swap

Given an array containing N elements. Find if it is possible to sort it in non-decreasing order using atmost one swap.

**Examples:**

Input :arr[] = {1, 2, 3, 4}

Output :YES

The array is already sorted

Input :arr[] = {3, 2, 1}

Output :YES

Swap 3 and 1 to get [1, 2, 3]

Input :arr[] = {4, 1, 2, 3}

Output :NO

A **simple approach** is to sort the array and compare the required position of the element and the current position of the element. If there are no mismatches, the array is already sorted. If there are exactly 2 mismatches, we can swap the terms that are not in the position to get the sorted array.

## C++

`// CPP program to check if an array can be sorted ` `// with at-most one swap ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `bool` `checkSorted(` `int` `n, ` `int` `arr[]) ` `{ ` ` ` `// Create a sorted copy of original array ` ` ` `int` `b[n]; ` ` ` `for` `(` `int` `i = 0; i < n; i++) ` ` ` `b[i] = arr[i]; ` ` ` `sort(b, b + n); ` ` ` ` ` `// Check if 0 or 1 swap required to ` ` ` `// get the sorted array ` ` ` `int` `ct = 0; ` ` ` `for` `(` `int` `i = 0; i < n; i++) ` ` ` `if` `(arr[i] != b[i]) ` ` ` `ct++; ` ` ` `if` `(ct == 0 || ct == 2) ` ` ` `return` `true` `; ` ` ` `else` ` ` `return` `false` `; ` `} ` ` ` `// Driver Program to test above function ` `int` `main() ` `{ ` ` ` `int` `arr[] = {1, 5, 3, 4, 2}; ` ` ` `int` `n = ` `sizeof` `(arr) / ` `sizeof` `(arr[0]); ` ` ` `if` `(checkSorted(n, arr)) ` ` ` `cout << ` `"Yes"` `; ` ` ` `else` ` ` `cout << ` `"No"` `; ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

## Python 3

# A linear Python 3 program to check

# if array becomes sorted after one swap

def checkSorted(n, arr):

# Create a sorted copy of

# original array

b = []

for i in range(n):

b.append(arr[i])

b.sort()

# Check if 0 or 1 swap required

# to get the sorted array

ct = 0

for i in range(n):

if arr[i] != b[i]:

ct += 1

if ct == 0 or ct == 2:

return True

else:

return False

# Driver Code

if __name__ == ‘__main__’:

arr = [1, 5, 3, 4, 2]

n = len(arr)

if checkSorted(n, arr):

print(“Yes”)

else:

print(“No”)

# This code is contributed

# by Rituraj Jain